Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
yield from
#5
# removed the * in front of iterables
print("Definition of generator-function")


def join(iterables, joiner):
    print("First step of generator")
    # spliting iterable in first iterable and the rest
    first, *rest = iterables

    # yield each element from first
    yield from first
    # here the generator pauses until
    # next iteration

    print("Second step of generator")
    for iterable in rest:
        # yield joiner
        print("yield")
        yield joiner

        # yield each element from iterable from rest
        print("yield from")
        yield from iterable


# example
my_iterables = (
    range(3),
    range(4),
    range(2),
)
print("Calling generator-function")
gen = join(my_iterables, "-")
# generator
print("Generator:", gen)
print("Code inside the generator is not executed yet")
print("Iterating over generator with list(gen)")
print()
result = list(gen)  # <- this consumes the generator

# Now the generator is empy
print("Trying to consume gen again: ", list(gen))
print("But the generator is exhausted.")
print("Example with a for-loop")
print()
for element in join(my_iterables, "-"):
    print(element, type(element))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
yield from - by akbarza - Apr-19-2024, 07:55 AM
RE: yield from - by Larz60+ - Apr-19-2024, 08:52 AM
RE: yield from - by deanhystad - Apr-19-2024, 01:22 PM
RE: yield from - by snippsat - Apr-19-2024, 02:44 PM
RE: yield from - by DeaD_EyE - Apr-19-2024, 07:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  yield usage as statement or expression akbarza 5 916 Oct-23-2023, 11:43 AM
Last Post: Gribouillis
  Using list comprehension with 'yield' in function tester_V 5 1,344 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Yield generator weird output Vidar567 8 3,355 Nov-23-2020, 10:59 PM
Last Post: deanhystad
  Trying to access next element using Generator(yield) in a Class omm 2 2,034 Oct-19-2020, 03:36 PM
Last Post: omm
  Yield statement question DPaul 6 2,571 Sep-26-2020, 05:18 PM
Last Post: DPaul
  Problem about yield, please help!! cls0724 5 2,928 Apr-08-2020, 05:37 PM
Last Post: deanhystad
  does yield support variable args? Skaperen 0 1,707 Mar-03-2020, 02:44 AM
Last Post: Skaperen
  generator function that yield from a list buran 9 4,333 Jun-04-2019, 10:26 PM
Last Post: snippsat
  yield help chakox 5 3,339 Apr-13-2019, 09:42 PM
Last Post: chakox
  Multiple calls to Python interpreter embedded in C++ application yield segmentation f mmoelle1 0 2,875 Mar-21-2019, 08:54 PM
Last Post: mmoelle1

Forum Jump:

User Panel Messages

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