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)
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With