Skip to content Skip to sidebar Skip to footer

Foreach In Python Not Working As Expected

I want to toggle every second element of a list: s = [False] * 5 for item in s[::2]: item = not item print(s) But it doesn't work. [False, False, False, False, False] This

Solution 1:

Because when you do

item = not item

What you're actually doing is to change the reference to an object in the array with another reference to an object outside the array. item is just a copy of a reference to an object inside the array.

The second code works as expected because it changes the reference in the array itself, not in a reference copy.

Solution 2:

These lines:

for item in s[::2]:
    item = not item

are equivalent to this:

for i in range(0, len(s), 2):
    item = s[i]
    item = not item

Solution 3:

In the first case you're assigning to the variable created during the loop. In the second you're assigning to an index in the array. Each iteration of the loop will reset the variable item.

Post a Comment for "Foreach In Python Not Working As Expected"