Search code examples
pythonenumerate

Python: "int" object is not iteratable in nested enumerate(list)


I am trying to iterate over every element of list b:

a = [1, 2, 3, 4]
b = [1, 2, 3, 4]

for cnt1, a in enumerate(a):
    print ("a:",cnt1, a)
    for cnt2, b in enumerate(b):
        print ("b:", cnt2, b)

However, I always get a "TypeError: 'int' object is not iterable" at the inner loop for the second iteration of a.

Expected:
a: 0 1
b: 0 1
b: 1 2
b: 2 3
b: 3 4
a: 1 2
b: 0 1
...
b: 3 4
a: 2 3
...

Actual:
a: 0 1
b: 0 1
b: 1 2
b: 2 3
b: 3 4
a: 1 2
TypeError: 'int' object is not iterable at: for cnt2, b in enumerate(b):


Solution

  • As Iain pointed out in the comments, You're redefining a and b in the loop, this will fix the issue.

    a = [1, 2, 3, 4]
    b = [1, 2, 3, 4]
    
    for cnt1, ele1 in enumerate(a):
        print ("a:",cnt1, ele1)
        for cnt2, ele2 in enumerate(b):
            print ("b:", cnt2, ele2)