liv2hak liv2hak - 17 days ago 9
Python Question

Converting generator object to a list

I am trying to wrap my head around

generator
and
yield
in python. I understand that a function that has an yield returns a generator object. However if I try to convert that generator object to a list it hangs my machine. I am trying to figure out why that is. And what is a more elegant way if any to convert a generator object to a list.

def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

a = fib()
print(type(a))

b = fib()
print(type(b))

print(list(b))


Output

<class 'generator'>
<class 'generator'>

Answer

The problem is that your generator has no end condition (while True and no break)

Even if it could make sense to write such a generator (ex: yield all the decimals of Pi or the Fibonacci sequence I just recognized in your code :)), when you convert it to a list, it loops forever (and eats all the memory too)

BTW: list() is of course the best way to turn a (finite :)) generator to a list object.