list comprehension misbehaving
Tim Chase
python.list at tim.thechases.com
Thu Mar 28 11:44:51 EDT 2013
On 2013-03-28 15:25, Wolfgang Maier wrote:
> Dear all, with
> a=list(range(1,11))
>
> why (in Python 2.7 and 3.3) is this explicit for loop working:
> for i in a[:-1]:
> a.pop() and a
As you discover:
> Especially, since these two things *do* work as expected:
> [a.pop() and a[:] for i in a[:-1]]
it's because you're taking a snapshot copy of "a" in the middle of
the loop. In your first example, if you change it to
results = []
for i in a[:-1]:
results.append(a.pop() and a)
print results
you get the same thing as your list comprehension because each item
in "results" refers to the now-(mostly)empty "a".
-tkc
More information about the Python-list
mailing list