close

How to convert generator object into list?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert generator object into list in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to convert generator object into list?

  1. How to convert generator object into list?

    To convert a generator expression into a list it is sufficient to do:
    list(<generator expression>)

  2. convert generator object into list

    To convert a generator expression into a list it is sufficient to do:
    list(<generator expression>)

Method 1

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

Method 2

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.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read