Using understanding as a shortcut to invoke a method multiple times

Possible duplicate:
Is Pythonic using lists for side effects only?

Sometimes in a script file I write something like [foo(x) for x in (1,2,3)]. I really don't care about the return value (if any), I just prefer shorthand rather than using

for x in (1,2,3):
  foo(x)

But in this sense, I create a list object that doesn’t actually go anywhere (I think it gets garbage because no one refers to it?)

>>> L = list('SxPyAMz')
>>> [L.remove(c) for c in ('x', 'y', 'z')]
[None, None, None]
>>> print L
['S', 'P', 'A', 'M']

My question is: is this bad practice, or is it completely harmless to the object so that the whistle is imperceptible? If this is bad, is there a better 1-liner for these shortcuts?

+5
source share
3 answers

- . consume itertools, , C .

0- deque throwaway / .

L = list('SxPyAMz') 
deque((L.remove(c) for c in ('x', 'y', 'z')), maxlen=0)

, 0- deque:

_consumer = deque(maxlen=0)
do_all = _consumer.extend

L = list('SxPyAMz') 
do_all(L.remove(c) for c in ('x', 'y', 'z'))
print L
+3

, , , , , , .

, , .

+7

, "" :

for c in ('x', 'y', 'z'): L.remove(c)
+6

All Articles