User avatar
jadro
Posts: 404
Joined: Sun Oct 02, 2016 1:20 pm
Location: Croatia

Print from function with yield

Thu Jun 06, 2019 8:04 pm

I learn Python and need help...
Why this code prints all numbers

Code: Select all

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step

for x in my_range(1, 10, 0.5):
    print(x)
but this dont:

Code: Select all

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step
    
(print(x) for x in my_range(1, 10, 0.5))
#or
print(x for x in my_range(1, 10, 0.5))
Thanx,
Jadro
Oracle backend database developer
SmartHome IoT & Microprocessor enthusiast and hobbyist

User avatar
Paeryn
Posts: 2604
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Print from function with yield

Fri Jun 07, 2019 12:43 am

jadro wrote:
Thu Jun 06, 2019 8:04 pm
I learn Python and need help...
Why this code prints all numbers

Code: Select all

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step

for x in my_range(1, 10, 0.5):
    print(x)
but this dont:

Code: Select all

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step
    
(print(x) for x in my_range(1, 10, 0.5))
#or
print(x for x in my_range(1, 10, 0.5))
Thanx,
Jadro
That is because

Code: Select all

x for x in my_range(1, 10, 0.5)
is an iterator and you asked to print the iterator itself (the <generator object>) rather than iterating over it to get the values.

Your first version is an iterator that prints the next number in the range each time you iterate over it

Code: Select all

>>> y = (print(x) for x in my_range(1, 10, 0.5))
>>> next(y)
1
>>> next(y)
1.5
Whereas the second version returns the next number in the range each time

Code: Select all

>>> z = (x for x in my_range(1, 10, 0.5))
>>> a = next(z)
>>> print(a)
1
>>> a = next(z)
>>> print(a)
1.5
Were you thinking about list comprehension (which is where you'd most likely see it) to create a list of all the values?

Code: Select all

>>> print([x for x in my_range(1, 10, 0.5)])
[1, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]
She who travels light — forgot something.

User avatar
jadro
Posts: 404
Joined: Sun Oct 02, 2016 1:20 pm
Location: Croatia

Re: Print from function with yield

Fri Jun 07, 2019 6:06 am

Thanx, I did not know this, I thought that printing wil trigger next somehow.
learn the whole life :-)

Jadro
Oracle backend database developer
SmartHome IoT & Microprocessor enthusiast and hobbyist

Return to “Python”