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)

It might be a nub question, but isn't it an understanding of lists that create a new list that we don’t need and just take up memory? It would not be better if we could make a list comprehension similar to an iterator.

+3
source share
3 answers

Yes (for both issues).

Using brackets instead of brackets, you can make a so-called generator expression for this sequence, which does exactly what you suggested. It allows you to iterate over a sequence without selecting a list to store all elements at once.

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

PEP 289.

+9

:

for x in some_list:
    do_something_with(x.attr)
+1

functional-programming , :

from operator import itemgetter

map(do_something_with, map(itemgetter('attr'), some_list))

Python 3 map()uses an iterator, but Python 2 creates a list. For Python 2, use instead itertools.imap().

If you return some_list, you can simplify it using a generator expression and lazy evaluation:

def foo(some_list):
    return (do_something_with(item.attr) for item in some_list)
0
source

Source: https://habr.com/ru/post/1724790/


All Articles