The Python assignment operator binds a value to a name. Your loop for i in seq
binds a value from seq
to the local name i
on every iteration. i = 100
then binds the value 100
to i
. This does not affect the original sequence, and the binding will be changed again in the next iteration of the loop.
You can use enumerate
to list the indices along with the values of seq
and perform the binding that way:
def f1(seq):
for i, n in enumerate(seq):
if n == 5:
seq[i] = 100
return seq
Even simpler may be to just iterate over the indices:
def f2(seq):
for i in range(len(seq)):
if seq[i] == 5:
seq[i] = 100
return seq
The options shown above will modify the sequence in-place. You do not need to return it except for convenience. There are also options for creating a new sequence based on the old one. You can then rebind the variable d
to point to the new sequence and drop the old one.
The easiest and probably most Pythonic method would be using a list comprehension:
d = [5, 1, 1, 1, 5]
d = [100 if x == 5 else x for x in d]
You can also use map
:
d = list(map(lambda x: 100 if x == 5 else x, d))
The output of map
is a generator, so I have wrapped it in list
to retain the same output type. This would not be necessary in Python 2, where map
already returns a list.