Cheatsheet: Data Structures
    Array / List
    Map / Dict
    Set
    Tuple
    Struct / Data Class
    Stacks
    Other Data Structures
    Collection Conversions
Cheatsheet: Control Flow
Cheatsheet: Class

Polyglot CheatSheet - Generators

Updated: 2022-04-04

Python

def foo():
    yield 1
    yield 2
    yield 3
  • returns a list: [x for x in range(3)]
  • returns a generator: (x for x in range(3))

List comprehensions can cause problems for large inputs by using too much memory.

Generator expressions don’t materialize the whole output sequence when they’re run. Instead, generator expressions evaluate to an iterator that yields one item at a time from the expression.

next() will return the next value, until it is exhausted:

>>> a = (x for x in range(3))
>>> next(a)
0
>>> next(a)
1
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Generator is composable

>>> a = (x for x in range(3))
>>> b = (y for y in a)
>>> next(b)
0
>>> next(b)
1

A recursive generator that generates Tree leaves in in-order.

def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x

        yield t.label

        for x in inorder(t.right):
            yield x

JavaScript

function* foo() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = foo();

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3