Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python generator function produces values one at a time: calling it creates a generator iterator, and each yield gives the next value while pausing the function until it is advanced again. Use a generator when code can process results incrementally instead of building the entire result in memory first.

What is a generator function in Python?

A generator function is a function that contains a yield expression. Unlike an ordinary function call that runs and returns a result, calling a generator function returns a generator iterator; its body starts when that iterator is advanced. The Python Language Reference describes it simply: “When a generator function is called, it returns an iterator known as a generator.” (Python Language Reference)

A generator is one kind of iterator, but not every iterator is a generator. A generator is typically used as a single-pass sequence: after it is exhausted, create a new generator by calling the function again if you need to produce the values again.

What does yield do?

yield produces a value and suspends execution of the generator. When the generator is advanced again, execution continues after the yield with its local variables and other execution state preserved. The Python Glossary says each yield “temporarily suspends processing, remembering the execution state (including local variables and pending try-statements).” (Python Glossary)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

That makes yield different from return: yield hands a value to the caller and pauses; return ends the generator. A generator can yield several values over its lifetime, then finish.

Practical example: generate values with a function

def count_up_to(limit):
    number = 1
    while number <= limit:
        yield number
        number += 1

for value in count_up_to(3):
    print(value)

The loop prints 1, 2, and 3. Calling count_up_to(3) creates the generator; the for loop advances it. Each time execution reaches yield number, the current number is produced and the function pauses. On the next iteration, it resumes and increments number.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Consume a generator with for or next()

A for loop is the usual way to consume generated values. It requests values until the generator finishes and handles the end-of-iteration signal for you.

Use next() when you want to advance an iterator explicitly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
def count_up_to(limit):
    number = 1
    while number <= limit:
        yield number
        number += 1

gen = count_up_to(2)
print(next(gen))  # 1
print(next(gen))  # 2
# Another next(gen) raises StopIteration

When the function exits without yielding another value, advancing the generator raises StopIteration. A normal for loop treats that as completion. The generator is then exhausted; it does not restart automatically. (Python Language Reference)

Generator expression or list comprehension?

Choose based on whether you need a list immediately or can consume values as they are produced. A list comprehension builds a list; a generator expression produces an iterator that yields the corresponding values as needed.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Choice Example What it produces Use it when
List comprehension [number * number for number in range(10)] A materialized list of all results You need the complete list, for example to index it or reuse it.
Generator expression (number * number for number in range(10)) An iterator that yields results when consumed Downstream code can process values sequentially rather than requiring the whole result at once.
Generator function A function containing one or more yield expressions A generator iterator with state and step-by-step logic Producing values requires multiple statements, branching, or retained state.

For example, if a consumer can handle each square in turn, a generator expression can avoid materializing the full result at once. That is a memory-use option, not a promise that generators are always faster. (Python Functional Programming HOWTO)

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Delegate values with yield from

Use yield from when a generator should pass values from another iterable or subgenerator through to its caller:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
def combined(first, second):
    yield from first
    yield from second

When the caller advances combined(first, second), it receives the values from first, followed by those from second. The yield from expression delegates to the iterable; when the delegated subgenerator completes, its return value can become the value of that expression. Delegation also passes through generator control methods such as send() and throw() when the underlying iterator supports them. (Python Language Reference)

Advanced: send a value into a generator

Generators can also receive data. The first advancement starts the generator and reaches its first yield. A later send(value) resumes execution, and the suspended yield expression evaluates to that sent value.

def running_total():
    total = 0
    while True:
        value = yield total
        if value is None:
            return
        total += value

gen = running_total()
print(next(gen))       # 0; starts the generator
print(gen.send(5))     # 5
print(gen.send(3))     # 8
gen.send(None)         # ends the generator

This pattern is useful when a generator needs input as well as producing output, but ordinary iteration is simpler for most value-producing tasks. (Python Functional Programming HOWTO)

Keep asynchronous generators distinct

The examples above use synchronous def functions and ordinary for loops. An async def function containing yield defines an asynchronous generator, which is consumed through asynchronous iteration rather than an ordinary for loop. (Python Language Reference)

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Further reading

For a deeper treatment of iterators, generators, lazy evaluation, and yield from, see Fluent Python, 2nd Edition by Luciano Ramalho. O’Reilly classifies it as intermediate to advanced; Chapter 17 covers these topics.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.