list comprehension misbehaving

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Thu Mar 28 16:25:14 CET 2013


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]

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

Thanks for your help,
Wolfgang




More information about the Python-list mailing list