1

Could anyone, please, explain what exactly happens in the following code to the "element" during iteration?

array = [2,3,4]
for element in array:
    element = 3
print(array)

>>>[2, 3, 4]

Output is [2, 3, 4] instead of [3, 3, 3]

Did I understand it correctly that when using "for element in l" syntax, we can only reference but not modify each element of an array of what does happen here?

P.S. I've seen the question named "why shouldn't you iterate like 'for element in array' ", but I couldn't find that one, so I asked it in this way. Seems like I found one of the disadvantages of iterating in this way. Please, redirect me to the mentioned question if possible.

  • 3
    its not even a reference, its more accurate to think of it as an assignment. so, `element = array[0] `for the first pass. after that, you just rebind the `element` name to something else. `array` has no reason to change. – Paritosh Singh Dec 28 '18 at 18:23

3 Answers3

2

Explanation

In the above example any changes to variable element in the loop is not possible.

Code

To get your expected output try this:

array = [2,3,4]
for i in range(len(array)):
    array[i] = 3
print(array)
0

When the iteration start element variable already has the current value in the array. when you assign 3 to it it will contain it until the next iteration when it will again take the current value of the array and so on. To get [3, 3, 3] you need to do it as the following:

array = [2,3,4]
for i in range(0,len(array)):
    array[i]=3
print(array)
Walid Da.
  • 948
  • 1
  • 7
  • 15
0

That's because element is a local variable in the scope of the for loop.

Run this snippet. I hope it can be self-explanatory (I used e instead of element), also I used enumerate to get the index:

array = [2,3,4]
for i, e in enumerate(array):
    print('i =', i, 'e =', e)
    e = 100
    print('e = 100-->','e =', e, 'but array[i]=',array[i])
    array[i] = e
    print('array[i] = e --> array[i]=',array[i])
    print('-'*10)

print(array) #=> [100,100,100]


Quick explanation

e and i are local variables which receive the value of the element and the index of the array at each iteration. Inside the loop you can change the value of e but it doesn't affect the the array. To change the value inside the array it is required to access it by index (array[i]).

karel
  • 5,489
  • 46
  • 45
  • 50
iGian
  • 11,023
  • 3
  • 21
  • 36