1

In the following code snippet , I am confused as to why the first element of a list can be used to iterate another list. Can someone please explain why this does not just print the integer 0 six times?

idx = [0,0,0]

junk = [1, 2, 3, 4, 5,6]

for idx[0] in junk:

    print(idx[0])
matt
  • 43
  • 6

4 Answers4

0

Because the for-loop assigns to the loop variable (idx[0] in your case). And that is allowed in your example.

You have ended up modifying the idx array by doing this:

idx = [0,0,0]

junk = [1, 2, 3, 4, 5,6]

for idx[0] in junk:

    print(idx[0])

print(idx)

Output:

1
2
3
4
5
6
[6, 0, 0]  # idx[0] is 6, the last value assigned to it by the for-loop
rdas
  • 20,604
  • 6
  • 33
  • 46
0

You code looks weird. You store the looping number into idx[0] that way - you can see that by printing it:

idx = [0,0,0]

junk = [1, 2, 3, 4, 5,6]

for idx[0] in junk:
    print(idx[0], idx)

to get

1 [1, 0, 0]
2 [2, 0, 0]
3 [3, 0, 0]
4 [4, 0, 0]
5 [5, 0, 0]
6 [6, 0, 0]

So you are activly changing the value of idx[0] on each iteration - how many iterations are done is ruled by junk's values.

You can create a "creative/inefficient" list-copy by that:

junk = [1, 2, 3, 4, 5,6]
idx = [0] * len(junk)
for i,idx[i] in enumerate(junk): 
    pass

although I have no clue whatfor one would need that :D

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

for idx[0] in junk: changes the idx[0] in each iteration. Add print(idx) to see that. Use for i in junk: to loop over junk.

rpoleski
  • 988
  • 5
  • 12
0

Because it is iterator protocol. Everytime you iterate through junk it will set the idx[0] to next value. You might think it behaves like the code below;

idx = [0, 0, 0]
junk = [1, 2, 3, 4, 5, 6]

junk = iter(junk)
idx[0] = next(junk)
idx[0] = next(junk)
idx[0] = next(junk)
idx[0] = next(junk)
idx[0] = next(junk)
idx[0] = next(junk)
print(idx[0])