-1

I have a list defined and it gets iter() applied to it. It then goes through a for loop and inside the for loop it gets enumerate(). I want it to print out the output 4 times because it is in the range of 4. Can anyone look and see what the problem might be? I

list_1 = [1,2,3,4,5]
list_1 = iter(list_1)

for x in range(2):
    for y,z in enumerate(list_1):
        print(str(y)+" "+str(z))

output:

0 1
1 2
2 3
3 4
4 5

desired output:

0 1
1 2
2 3
3 4
4 5
0 1
1 2
2 3
3 4
4 5
S.McWhorter
  • 151
  • 1
  • 1
  • 15
  • 5
    remove the line `list_1 = iter(list_1)`. – timgeb Nov 09 '18 at 17:37
  • 3
    When you use the `iter` function you create an iterable that is consumed. So after the first `range` iteration there is nothing left in `list_1`. – Alex Nov 09 '18 at 17:38
  • 3
    `iter(..)` generates an iterator over the list. That means at the end of the outer `for` loop, the iterator is "exhausted". so the second time you enter the `for`, there are no elements in it anymore. – Willem Van Onsem Nov 09 '18 at 17:38
  • 2
    (I'm also trying to find the duplicate that asks "why is my result empty after iterating twice?") – timgeb Nov 09 '18 at 17:39
  • 1
    @timgeb, I think I found a good target, but feel free to change / add. – jpp Nov 09 '18 at 17:42
  • What if I need it to be iterable... how would i go about this? – S.McWhorter Nov 09 '18 at 19:21

1 Answers1

1

Python list is iterable. You don't need to use iter().

list_1 = [1,2,3,4,5]

for x in range(2):
    for y,z in enumerate(list_1):
        print(str(y)+" "+str(z))

Out:

0 1
1 2
2 3
3 4
4 5
0 1
1 2
2 3
3 4
4 5
Geeocode
  • 5,705
  • 3
  • 20
  • 34
  • I'm just using this as an example. I need my list to be iterable.. How could I do this while making my list iterable? – S.McWhorter Nov 09 '18 at 19:21
  • @S.McWhorter I'm not sure I see you. You wan't iterate an object which is use iter() in any way? – Geeocode Nov 09 '18 at 23:09