# How do Python generators and comprehensions map to Rust iterators?
Source: https://ruststudio.org/community/t/59/how-do-python-generators-and-comprehensions-map-to-rust-iterators
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, Python 3.13.7, Windows 11
Category: Help and questions | Kind: FAQ | Tags: porting, python, iterators | Views: 0

## Short answer
A generator expression or comprehension becomes a chain of iterator adapters such as filter and map, ended by sum or collect. Both are lazy, so nothing runs until the end of the chain asks for values. A generator function with yield becomes a struct that implements Iterator and keeps the state.

## Answer
## Answer
Python's lazy sequences (generator expressions, `map`, `filter`, functions with `yield`) and Rust's iterators work the same way: each step asks the previous one for the next value, and no work happens before something consumes the sequence. That makes the port mostly mechanical for chains, and structural for `yield`.

| Python | Rust |
|---|---|
| `[f(x) for x in xs if p(x)]` | `xs.iter().filter(p).map(f).collect::<Vec<_>>()` |
| `sum(x * x for x in xs)` | `xs.iter().map(square).sum()` (with a function `square`) |
| `any(...)`, `all(...)` | `.any(...)`, `.all(...)` |
| `enumerate(xs)`, `zip(a, b)` | `.enumerate()`, `.zip(b)` |
| `itertools.islice(g, n)` | `.take(n)` |
| a function with `yield` | a struct that implements `Iterator` (no stable `yield`) |
| `{k: v for ...}` | `.collect::<HashMap<_, _>>()` |

Python (3.13.7), with a generator expression, a generator function and a visible side effect to show laziness:

```python
print(sum(x * x for x in range(10**6) if x % 3 == 0))

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

out = []
for x in fib():
    if x >= 100:
        break
    out.append(x)
print(out)
noisy = (print("  computing", x) or x * 10 for x in range(1, 4))
print("built the generator")
print(list(noisy))
```

```text
111111277777611111
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
built the generator
  computing 1
  computing 2
  computing 3
[10, 20, 30]
```

Rust (rustc 1.93.0), the same four steps:

```rust title=src/main.rs
fn main() {
    let total: u64 = (0..1_000_000u64).filter(|x| x % 3 == 0).map(|x| x * x).sum();
    println!("{total}");

    // Rust has no stable `yield`; a struct that implements Iterator holds the state that the generator kept.
    struct Fib { a: u64, b: u64 }
    impl Iterator for Fib {
        type Item = u64;
        fn next(&mut self) -> Option<u64> {
            let r = self.a;
            self.a = self.b;
            self.b += r;
            Some(r)
        }
    }
    let first: Vec<u64> = Fib { a: 0, b: 1 }.take_while(|&x| x < 100).collect();
    println!("{first:?}");

    // laziness: nothing below runs until the iterator is consumed
    let noisy = (1..=3).map(|x| { println!("  computing {x}"); x * 10 });
    println!("built the iterator");
    let v: Vec<i32> = noisy.collect();
    println!("{v:?}");
}
```

```text
111111277777611111
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
built the iterator
  computing 1
  computing 2
  computing 3
[10, 20, 30]
```

The outputs match line for line, apart from the words "generator" and "iterator". The number `111111277777611111` needs 64-bit arithmetic: Python's integers grow as needed, and the Rust code chose `u64` for it. With `u32` it would overflow, so the width is a decision the port must make (see the thread on integers).

## How to do it
1. Port comprehensions and generator expressions to adapter chains. Read the Python expression from the inside out: the `for` part is the source, `if` is `filter`, the leading expression is `map`.
2. Finish each chain with a consumer: `collect`, `sum`, `count`, `for` loop, `find`, `any`.
3. For a generator function, write a struct with the local variables as fields and put the body of one loop iteration in `next`. Return `None` where the generator returns.
4. A function that returns an iterator can return `impl Iterator<Item = T>`, without naming the adapter types.
5. Remember that borrowed iterators (`iter()`) yield references; use `.copied()` or `.cloned()` when you need values.

## Common mistakes
- Collecting into a `Vec` between every step. Each `collect` allocates; keep the chain lazy until the end.
- Expecting a lazy iterator to run when you drop it unused. Like Python generators, it does nothing until consumed (the compiler warns about unused iterator adapters).
- Looping with an index (`for i in 0..v.len()`) where an iterator would be shorter and avoids bounds checks.

## Related questions
### Is there something like `itertools`?
Many of its functions are in the standard library (`zip`, `chain`, `take`, `skip`, `step_by`, `windows`, `chunks`). The `itertools` crate has more; it was not run for this thread.

### Can I write generators with `yield` in Rust?
Not as a stable language feature as far as the Ruststudio team knows; this was not tested on rustc 1.93.0, so check the current release notes. Use a struct that implements `Iterator`, or a channel between two threads.

## Sources
- The Rust Book, "Processing a Series of Items with Iterators": https://doc.rust-lang.org/book/ch13-02-iterators.html
- `std::iter`: https://doc.rust-lang.org/std/iter/index.html
