Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output in Python Generators

I am trying to figure out generators in Python and i am trying to filter the list and square them and return the output.

list = [1, 4, -5, 10, -7, 2, 3, -1]

def square_generator(optional_parameter):
    return (x ** 2 for x in list if x > optional_parameter)
g = (square_generator(i) for i in list)

h = square_generator(0)
print h

What i am doing wrong ?


2 Answers

When you define a generator you must iterate over it like so:

for x in h:
    print x

If you just try to print the generator then you'll get the object:

<generator object <genexpr> at 0x02A4FB48>
like image 112
Ffisegydd Avatar answered May 24 '26 21:05

Ffisegydd


If you wanted to produce a list, just use a list comprehension:

def square_generator(optional_parameter):
    return [x ** 2 for x in somelist if x > optional_parameter]

or turn call list() on the generator (provided you didn't use list as a local name):

list(h)

Your generator is working just fine otherwise:

>>> somelist = [1, 4, -5, 10, -7, 2, 3, -1]
>>> def square_generator(optional_parameter):
...     return (x ** 2 for x in somelist if x > optional_parameter)
... 
>>> list(square_generator(0))
[1, 16, 100, 4, 9]
like image 44
Martijn Pieters Avatar answered May 24 '26 20:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!