-2

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):

riggedCoinflip
  • 435
  • 4
  • 16
  • 5
    You're redefining the variables `a` and `b` in your for loops. "for cnt1, __a__ in ..." – Iain Shelvington Dec 28 '19 at 17:46
  • 1
    Why are you shadowing the list you're iterating over with the loop variable? – jonrsharpe Dec 28 '19 at 17:46
  • 1
    Python's `for` loops are essentially `foreach` loops. They **assign** to the variable. in the second iteration, `a` is already an element of the list `a`. `enumerate`-ing an integer (`enumerate(a)`) does not make any sense – DeepSpace Dec 28 '19 at 17:50

1 Answers1

4

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)
Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24