Python Forum
Yield generator weird output
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Yield generator weird output
#1
Hello,

I would like to create function primes(), but when I return values from the first loop function stops.
Instead of return I try using yield, but it seems that I should make some additional code to it, because it outputs hexa code.

def primes(to_number = 5):
    #### define new list with range to_number + 1
    new_list = []
    for x in range(to_number + 1):
        for y in range(to_number + 1):
            new_list.append(y)
        yield new_list
*When I use return it's all good, but I have something more to say.. in this code:)

return
[0, 1, 2, 3, 4, 5]
yield
<generator object primes at 0x00000298F858F7B0>
So question is, how to yield result without stopping the function?

Greetings,
V.
Reply
#2
Please show code where you use output of generator.
Reply
#3
What are you doing with the outer loop? I don't understand the purpose.

When you use yield instead of return, you turn the function into a generator.
As an example, here's a regular function
def squares():
    """Returns a list of the first 5 square numbers"""
    data = []
    for i in range(1,6):
        data.append(i)
    return data        # all the data is returned at once

print(squares())       # the function's data can be printed directly
Output:
[1, 2, 3, 4, 5]
And here is the function modified to be a generator. See that directly printing the return value just shows a note about the generator object, but either iterating over it or putting it into a container allows the object to produce the data.

def squares():
    """Yields the first 5 square numbers"""
    for i in range(1,6):
        yield i        # Data will be created by a generator

print(squares())       # the function's data cannot be printed directly
generator = squares()
print(list(generator))  # One way of consuming the iterator
Output:
<generator object squares at 0x10180b510> [1, 2, 3, 4, 5]
Reply
#4
Do you want primes() or primes(to_number)? Yield doesn't make much sense for primes(to_number). The to_number implies a bound result. If you want to generate arbitrarily large prime numbers then yield is the way to go.

Here's primes(to_number) using yield. I don't see this being any better than returning a list.
def primes(to_number):
    results = []
    for a in range(2, to_number):
        # All non-prime numbers are divisible by a prime
        for b in results:
            if a % b == 0:
                break;
        else:
            yield a
            results.append(a)

print(list(primes(10)))
This is primes() modified to go on forever. It is awkward to use.
def primes():
    results = []
    a = 2
    while True:
        # All non-prime numbers are divisible by a prime
        for b in results:
            if a % b == 0:
                break;
        else:
            yield a
            results.append(a)
        a += 1

# print primes <= 10
primes_list=[]
for x in primes():
    if x > 10:
        break
    primes_list.append(x)
print(primes_list)

# print first 10 primes
prime_gen = primes()
print([next(prime_gen) for x in range(10)])
Unbound generators create unbound sequences. Unbound sequences don't work in for loops. You need to provide additional logic to end the loop.

A generator is great when you have an infinite sequence. Infinite sequences are hard to use, but that is not the fault of yield. For a finite sequence you might still use a generator if the number of elements is large. Using a generator you don't have to store the entire sequence, only the current value. A generator is also good if the sequence will take a long time go produce. A generator yields early results quickly and the time to produce the entire sequence is divided into many short periods.
Reply
#5
def primes(to_number = 5):
 
    new_list = []
    for x in range(to_number + 1):
        for y in range(to_number + 1):
            new_list.append(y)
        return new_list

    isprime = bool(False)
    return isprime

print(primes())
Which gives me only new_list values then function stops, doesn't return isprime.
Both returns are in the same function, def.

EDIT:

It is the same situation which I do not understand, how to continue this function to the end.

def primes(to_number = 5):
 
    new_list = []
    for x in range(to_number + 1):
        return x
When I print it I get 0 as output.

How to change return to something else to allow to continue the loop.
Reply
#6
I don't understand anything about your code. The loops don't make any sense. Returning isprime doesn't make any sense.

I think you should describe what it is that you are trying to do. Don't try to describe it with a Python function, that isn't working. Just provide a simple description about what you want you function to do and what values(s?) it should return.
Reply
#7
def primes(to_number=100):
    lista = [2]
    for x in range(2, to_number):
        if x % 2 == 0:
            pass
        else:
            lista.append(x)
    return lista
result = primes()
print(result)
It works, thank you for answers.
Reply
#8
It's nice that it works. However, I suggest that you don't name this function 'primes'. This function has nothing to do with finding primes (except that primes are odd numbers so they are somewhere in returned list)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#9
This is the second time recently that I've seen a function named "prime" that returns odd numbers. Weird.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  yield usage as statement or expression akbarza 5 751 Oct-23-2023, 11:43 AM
Last Post: Gribouillis
  Using list comprehension with 'yield' in function tester_V 5 1,175 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Trying to access next element using Generator(yield) in a Class omm 2 1,932 Oct-19-2020, 03:36 PM
Last Post: omm
  Yield statement question DPaul 6 2,448 Sep-26-2020, 05:18 PM
Last Post: DPaul
  Problem about yield, please help!! cls0724 5 2,811 Apr-08-2020, 05:37 PM
Last Post: deanhystad
  how to output to stderr from inside a generator? Skaperen 2 1,780 Mar-03-2020, 03:17 AM
Last Post: Skaperen
  does yield support variable args? Skaperen 0 1,641 Mar-03-2020, 02:44 AM
Last Post: Skaperen
  Random Password Generator with Weird Output. Why? Selenestica 2 2,543 Sep-11-2019, 04:36 AM
Last Post: Selenestica
  generator function that yield from a list buran 9 4,103 Jun-04-2019, 10:26 PM
Last Post: snippsat
  yield help chakox 5 3,205 Apr-13-2019, 09:42 PM
Last Post: chakox

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020