There is another / shorter way to do this, but I would not call it more Pythonic:
generator = gen() directories = [] generator_wrapper = (directories.append(foo['name']) or foo for foo in generator)
This exploits the fact that append , like all mutating methods in Python, always returns None , so .append(...) or foo will always evaluate foo .
So the whole dictionary is still the result of a generator expression, and you still get a lazy rating, but the name is still stored in the directories list.
You can also use this method in an explicit for loop:
for foo in generator: yield directories.append(foo['name']) or foo
or even simplify the loop a bit:
for foo in generator: directories.append(foo['name']) yield foo
since there is no reason to use xrange only to iterate over the generator (unless you really want to just repeat a number of known steps).
source share