alter / modify a list as well as iterate on its items / objects

Peter Otten __peter__ at web.de
Wed May 26 05:04:29 EDT 2004


Derek Basch wrote:

> Can anyone point me towards an article or explain
> how to properly alter a list as well as iterate
> on its items? For example:
> 
> input:
> 
> word = ["albert", "likes", "surfing!"]
> 
> for word in sentence:
>     word += "foo"
> 
> result:
> 
> word = ["albertfoo", "likesfoo", "surfingfoo"]

Note that the solutions presented so far do *not* modify the list in place.
This is important if you keep references to the list elswhere. For example:

>>> backup = sample = ["alpha", "beta", "gamma"]
>>> sample = map(lambda x: x + ".suffix", sample)
>>> sample is backup
False
>>> sample = [x + ".suffix" for x in sample]
>>> sample is backup
False

Here are two ways to achieve inplace modification:

>>> backup = sample = ["alpha", "beta", "gamma"]
>>> for i, x in enumerate(sample):
...     sample[i] = x + ".suffix"
...
>>> sample is backup
True

>>> backup = sample = ["alpha", "beta", "gamma"]
>>> sample[:] = [x + ".suffix" for x in sample]
>>> sample is backup
True
>>>

Here the [:] slice on the left makes the difference.

Peter



More information about the Python-list mailing list