Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list comprehension equivalent without producing a throwaway list [duplicate]

Possible Duplicate:
Is it Pythonic to use list comprehensions for just side effects?
proper use of list comprehensions - python

Python has the useful and elegant list comprehension syntax. However AFAIK it always produces a list. Sometimes I feel the urge to use list comprehension just for its compactness and elegance without needing the resulting list:

[some_func(x) for x in some_list if x>5]

some_func() may return something which I don't need, it may not return anything at all. I tried the generator syntax:

(some_func(x) for x in some_list if x>5)

but as you may guess, it doesn't iterate over some_list. It does so only within certain context:

other_func(some_func(x) for x in some_list if x>5)

So... is there a syntax I'm missing to get this to work, or should I always fall back to 3 lines?

for x in some_list:
    if x>5:
        some_func(x)
like image 575
Jonathan Livni Avatar asked Jan 02 '12 07:01

Jonathan Livni


2 Answers

I don't now if you will find it elegant, but there is a consume recipe in the itertools docs that is very fast and will run an iterator to completion without building-up a list:

>>> consume(some_func(x) for x in some_list if x>5)
like image 185
Raymond Hettinger Avatar answered Sep 25 '22 21:09

Raymond Hettinger


Use a genex to get the appropriate values to iterate over.

for i in (x for x in some_list if x > 5):
    some_func(i)
like image 24
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 21:09

Ignacio Vazquez-Abrams