TypeError: 'int' object is not iterable error on a list

Question:

I am trying to use a for loop to go through a list and keep count, and using this value in other lists.

def boxplot(values_headers):
    """
    Creates a boxplot from the given values
    """
    categories = {}
    values = values_headers[0]
    headers1 = values_headers[1]
    tick_values = []
    
    print(headers1)
    print(type(headers1))
    
    for count in len(headers1):
        for individual_labels in values:
            individual_values = values[individual_labels]
            tick_values.append(int(individual_values[int(count)]))
        categories[headers1[count]] = tick_values
        tick_values = []

i tried to run this, with the print statements to see what was wrong.
and this is what it returned: (file-paths removed because of sensitive info)

['Fast-Food Chains', 'U.S. Systemwide Sales (Millions - U.S Dollars)', 'Average Sales per Unit (Thousands - U.S Dollars)', 'Franchised Stores', 'Company Stores', '2021 Total Units', 'Total Change in Units from 2020']
<class 'list'>
Traceback (most recent call last):
x
TypeError: 'int' object is not iterable

What is going wrong here?

Asked By: XDel

||

Answers:

len(headers1) returns an int, so as the interpreter says…you CANNOT iterate over an integer

for count in len(headers1)

If you want to iterate over a list and access indices use enumerate like this:

fruits = ["apple", "pear", "plum"]

for idx, fruit in enumerate(fruits):
    print(idx, fruit) # This will print 0 "apple", 1 "pear", 2 "plum"

For more info go to: https://docs.python.org/3/library/functions.html#enumerate

On the other hand if you want to iterate using only indices you can do it like this:

fruits = ["apple", "pear", "plum"]

for idx in range(len(fruits)):
    fruits[idx]... #  access using idx and process further

For more info go to: https://docs.python.org/3/library/functions.html#func-range
Note that this is not very "pythonic" though.

Third option is to iterate over elements of the iterable like this:

fruits = ["apple", "pear", "plum"]

for fruit in fruits:
    fruit # this "fruit" will be "apple", "pear", "plum" in subsequent iterations

And in general I’d recommend reading: https://docs.python.org/3/reference/compound_stmts.html#for

Answered By: Gameplay
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.