views:

127

answers:

2

What is the best way to do the following in Python:

for item in [ x.attr for x in some_list ]:
    do_something_with(item)

This may be a nub question, but isn't the list comprehension generating a new list that we don't need and just taking up memory? Wouldn't it be better if we could make an iterator-like list comprehension.

+9  A: 

Yes (to both of your questions).

By using parentheses instead of brackets you can make what's called a "generator expression" for that sequence, which does exactly what you've proposed. It lets you iterate over the sequence without allocating a list to hold all the elements simultaneously.

for item in (x.attr for x in some_list):
    do_something_with(item)

The details of generator expressions are documented in PEP 289.

Phil
Thanks. I didn't know you could use parenthesis like that :)
Discodancer
+1  A: 

Why not just:

for x in some_list:
    do_something_with(x.attr)
Paul McGuire
Well it's a bit more complicated than that in my case :) This was a simple example I gave to illustrate the point. I had to use reduce(), but now I can just do with any() and all() :)
Discodancer