ajknzhol
ajknzhol

Reputation: 6450

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 ?

Upvotes: 3

Views: 104

Answers (3)

Andreas Vinter-Hviid
Andreas Vinter-Hviid

Reputation: 1482

your square_generator function returns a generator object. Generators are iterators, and they are as such not lists but objects containing rules for generating the next element of a sequence.

So, when your function returns, it does not calculate the squares. They are calculated only when needed. Therefore you need to iterate over the sequence to get the elements. They simply does not exist before you request to see them.

This also means that when you have iterated over the list it disappears. If you want it to be persistent you have to look at Martin Pieters' answer i.e. use a list instead of a generator/iterator.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121952

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]

Upvotes: 3

Ffisegydd
Ffisegydd

Reputation: 53678

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>

Upvotes: 5

Related Questions