Nested for loop in 'lists' and 'iterators'

Viewed 1182

I have these two lists

l1 = [1,2,3]
l2 = [10,20,30]

I use this nested for loop to access all possible pairs:

for a in l1:
    for b in l2:
        print(a,b)

I get the following expected result:

1 10
1 20
1 30
2 10
2 20
2 30
3 10
3 20
3 30

But if I convert l1 and l2 to iterators, I get a different result and I can't access to all of the pairs:

l1=iter(l1)
l2=iter(l2)

for a in l1:
    for b in l2:
        print(a,b)

1 10
1 20
1 30

I can't understand the difference between these two code snippets. Why the iterators generate this result?

1 Answers
l2=iter(l2)

This creates an iterator out of l2. An iterator can only be iterated through once. After that, the interator is finished. If you wanted to iterate over l2 again, you'd need to create another iterator from it.

for a in l1:
    for b in l2:
        print(a,b)

This will try to iterate over l2 - once for each item in l1. If there are more than 1 items in l1, that won't work - because the l2 iterator is already exhausted after the first iteration.

So you need something like this:

l1 = iter(l1)

for a in l1:
    l2_iter = iter(l2)
    for b in l2_iter:
        print(a,b)

Which would do what you expect.

Related