For your example, @Korem
's suggestion of a list comprehension is the ideal solution.
But here's an alternative for when you encounter that pattern where you
- initialize an empty sequence
- append to it in a loop
- return the sequence
but maybe need to do some more heavy lifting that you can't simply express in an expression (list comprehensions don't allow statements, only epxressions) - create a generator function:
def bars(foos):
for foo in foos:
yield foo.bar
There's just two things to note:
- Generator functions don't return a sequence, they return a generator. That generator needs to be consumed by iterating over it. If you would use it like a sequence (indexing its elements for example), you'd need to turn it into a sequence e.g. by doing
list(bars(f))
:
>>> gen = bars(f)
>>> gen[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'generator' object has no attribute '__getitem__'
>>>
>>> list(gen)[0]
42
- Once you iterate over it the generator will be exhausted:
>>> gen = bars(f)
>>> list(gen)
[42, 42, 42]
>>> list(gen)
[]