简体   繁体   中英

TypeError: 'int' object is not iterable

There is an error when I execute This code-
for i in len(str_list): TypeError: 'int' object is not iterable

How would I fix it? (Python 3)

def str_avg(str):
    str_list=str.split()
    str_sum=0
    for i in len(str_list):
        str_sum += len(str_list[i])
    return str_sum/i

You are trying to loop over in integer; len() returns one.

If you must produce a loop over a sequence of integers, use a range() object :

for i in range(len(str_list)):
    # ...

By passing in the len(str_list) result to range() , you get a sequence from zero to the length of str_list , minus one (as the end value is not included).

Note that now your i value will be the incorrect value to use to calculate an average, because it is one smaller than the actual list length! You want to divide by len(str_list) :

return str_sum / len(str_list)

However, there is no need to do this in Python. You loop over the elements of the list itself . That removes the need to create an index first:

for elem in str_list
    str_sum += len(elem)

return str_sum / len(str_list)

All this can be expressed in one line with the sum() function , by the way:

def str_avg(s):
    str_list = s.split()
    return sum(len(w) for w in str_list) / len(str_list)

I replaced the name str with s ; better not mask the built-in type name, that could lead to confusing errors later on.

def str_avg(str):
    str_list = str.split()
    str_sum = len(''.join(str_list))  # get the total number of characters in str
    str_count = len(str_list)  # get the total words

    return (str_sum / str_count)

For loops requires multiple items to iterate through like a list of [1, 2, 3] (contains 3 items/elements).

The len function returns a single item which is an integer of the length of the object you have given it as a parameter.

To have something iterate as many times as the length of an object you can provide the len functions result to a range function. This creates an iterable allowing you to iterate as any times as the length of the object you wanted.

So do something like

for i in range(len(str_list)):

unless you want to go through the list and not the length of the list. You can then just iterate with

for i in str_list:

While running for loop we need to provide any iterable object. If we use len(str_list) then it will be an integer value. We can not make an integer iterable.

Solution - Using range() function.

for i in range(len(str_list)):

Get complete detail in this article. enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM