Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #42152 > unrolled thread

Re: list comprehension misbehaving

Started byPeter Otten <__peter__@web.de>
First post2013-03-28 16:48 +0100
Last post2013-03-28 16:48 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: list comprehension misbehaving Peter Otten <__peter__@web.de> - 2013-03-28 16:48 +0100

#42152 — Re: list comprehension misbehaving

FromPeter Otten <__peter__@web.de>
Date2013-03-28 16:48 +0100
SubjectRe: list comprehension misbehaving
Message-ID<mailman.3891.1364485670.2939.python-list@python.org>
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
> 
> giving:
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
> [1, 2, 3, 4, 5, 6, 7, 8]
> [1, 2, 3, 4, 5, 6, 7]
> [1, 2, 3, 4, 5, 6]
> [1, 2, 3, 4, 5]
> [1, 2, 3, 4]
> [1, 2, 3]
> [1, 2]
> [1]

No. Introduce a result list, and you'll see that you append the *same* list 
to the result nine times:

>>> a = range(1, 11)
>>> result = []
>>> for i in a[:-1]:
...     result.append(a.pop() and a)
... 
>>> result
[[1], [1], [1], [1], [1], [1], [1], [1], [1]]

> but the equivalent comprehension failing:
> [a.pop() and a for i in a[:-1]]
> 
> giving:
> [[1], [1], [1], [1], [1], [1], [1], [1], [1]]
> 
> ???
> Especially, since these two things *do* work as expected:
> [a.pop() and a[:] for i in a[:-1]]
> [a.pop() and print(a) for i in a[:-1]] # Python 3 only

So you already know the solution to your problem...

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web