List problem
Peter Hansen
peter at engcorp.com
Sun Oct 31 08:43:28 EST 2004
Reinhold Birkenfeld wrote:
> Alex Martelli wrote:
>> a[:] = [x for x in a if x != 2]
>
> ^^^
> What are these for?
Observe the difference between these two approaches:
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)]
>>> b = a = range(5)
>>> b is a
True
>>> a[:] = [x for x in a if x != 2]
>>> a
[0, 1, 3, 4]
>>> b
[0, 1, 3, 4]
>>> b is a
True
>>> b = a = range(5)
>>> a = [x for x in a if x != 2]
>>> b is a
False
[:] on the left side of the assignment basically causes
"slice assignment" to the whole list, modifying it in-place
instead of creating a new list.
-Peter
More information about the Python-list
mailing list