'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


Solution 1:[1]

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.

Solution 2:[2]

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:

Solution 3:[3]

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)

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martijn Pieters
Solution 2 Aklys
Solution 3
Solution 4 benson23