Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a generator expression from a list in python

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.

like image 268
disc0dancer Avatar asked Mar 13 '26 03:03

disc0dancer


2 Answers

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.

like image 176
Phil Avatar answered Mar 16 '26 00:03

Phil


Why not just:

for x in some_list:
    do_something_with(x.attr)
like image 39
PaulMcG Avatar answered Mar 15 '26 22:03

PaulMcG