python - How to convert generator object into list?

ID : 274367

viewed : 45

Tags : pythonlistgeneratorpython





Top 2 Answer for python - How to convert generator object into list?

vote vote

90

If you actually need a list, you can just do:

lst = list(generator_object) 

However, if all you want is to iterate through the object, you do not need a list:

for item in generator_object:     # do something with item 

For example,

sqr = (i**2 for i in xrange(10)) # <generator object <genexpr> at 0x1196acfa0> list(sqr) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]  sqr = (i**2 for i in xrange(10)) for x in sqr:     print x, # 0 1 4 9 16 25 36 49 64 81 
vote vote

81

To convert a generator expression into a list it is sufficient to do:

list(<generator expression>) 

Beware though if the generator expression can generate an infinite list, you will not get what you expect.

Top 3 video Explaining python - How to convert generator object into list?







Related QUESTION?