Unique id generator

Unique id generator

EasyIterator & Generator Programs · 14 of 20

Write a generator that produces ids like TC-001, TC-002, …

Output
TC-001 TC-002 TC-003

Approach

  1. itertools.count gives an endless counter.

Solution

Python
from itertools import count def test_ids(prefix="TC"):    for n in count(1):        yield f"{prefix}-{n:03}" ids = test_ids()print(next(ids), next(ids), next(ids))
Output
TC-001 TC-002 TC-003

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Cycle through values

Cycle through values

EasyIterator & Generator Programs · 15 of 20

Write a Python program that assigns browsers to 7 tests in rotation.

Output
test 1 -> chromium
test 2 -> firefox
test 3 -> webkit
test 4 -> chromium
test 5 -> firefox
test 6 -> webkit
test 7 -> chromium

Approach

  1. itertools.cycle repeats a sequence forever.

Solution

Python
from itertools import cycle browsers = cycle(["chromium", "firefox", "webkit"])for test in range(1, 8):    print(f"test {test} -> {next(browsers)}")
Output
test 1 -> chromium
test 2 -> firefox
test 3 -> webkit
test 4 -> chromium
test 5 -> firefox
test 6 -> webkit
test 7 -> chromium

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Running total

Running total

EasyIterator & Generator Programs · 13 of 20

Write a generator that yields the running total of a list.

Output
[5, 8, 16, 18] [5, 8, 16, 18]

Approach

  1. Keep a total and yield after each addition; compare with itertools.accumulate.

Solution

Python
from itertools import accumulate def running_total(numbers):    total = 0    for n in numbers:        total += n        yield total print(list(running_total([5, 3, 8, 2])), list(accumulate([5, 3, 8, 2])))
Output
[5, 8, 16, 18] [5, 8, 16, 18]

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Generator pipeline

Generator pipeline

MediumIterator & Generator Programs · 10 of 20

Write a pipeline of generators that reads numbers, keeps the even ones and squares them.

Output
[4, 16, 36, 64, 100]

Approach

  1. Each generator consumes the previous one.

Solution

Python
def numbers(limit):    yield from range(1, limit + 1) def only_even(source):    for n in source:        if n % 2 == 0:            yield n def squared(source):    for n in source:        yield n * n print(list(squared(only_even(numbers(10)))))
Output
[4, 16, 36, 64, 100]

Line by line

Line 2

yield from hands out every value of another iterable.

Line 13

Only one value at a time moves through the pipeline.

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Split a list into chunks

Split a list into chunks

EasyIterator & Generator Programs · 11 of 20

Write a generator that yields chunks of a given size.

Input
1..10, size 3
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Approach

  1. Slice from each start index.

Solution

Python
def chunks(items, size):    for i in range(0, len(items), size):        yield items[i:i + size] print(list(chunks(list(range(1, 11)), 3)))
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Flatten nested lists with yield from

Flatten nested lists with yield from

MediumIterator & Generator Programs · 12 of 20

Write a recursive generator that flattens nested lists.

Output
[1, 2, 3, 4, 5]

Approach

  1. yield from the recursive call for each sub-list.

Solution

Python
def flatten(items):    for item in items:        if isinstance(item, list):            yield from flatten(item)        else:            yield item print(list(flatten([1, [2, [3, [4]]], 5])))
Output
[1, 2, 3, 4, 5]

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Read a file lazily

Read a file lazily

EasyIterator & Generator Programs · 9 of 20

Write a generator that yields non-empty, stripped lines from a file.

Output
['start', 'step 1', 'end']

Approach

  1. Loop over the file inside the generator.

Solution

Python
with open("log.txt", "w") as f:    f.write("start\n\n  step 1  \nend\n") def clean_lines(path):    with open(path) as f:        for line in f:            line = line.strip()            if line:                yield line print(list(clean_lines("log.txt")))
Output
['start', 'step 1', 'end']

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Iterable class with a generator method

Iterable class with a generator method

EasyIterator & Generator Programs · 8 of 20

Write a class whose objects can be looped over many times.

Output
['Song A', 'Song B'] ['Song A', 'Song B']

Approach

  1. Make __iter__ a generator; every loop gets a fresh one.

Solution

Python
class Playlist:    def __init__(self, *songs):        self.songs = songs     def __iter__(self):        for song in self.songs:            yield song p = Playlist("Song A", "Song B")print(list(p), list(p))
Output
['Song A', 'Song B'] ['Song A', 'Song B']

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Custom iterator class

Custom iterator class

MediumIterator & Generator Programs · 7 of 20

Write an iterator class that returns the characters of a word in reverse.

Output
nohtyp

Approach

  1. Implement __iter__ and __next__.

Solution

Python
class Reverse:    def __init__(self, text):        self.text = text        self.index = len(text)     def __iter__(self):        return self     def __next__(self):        if self.index == 0:            raise StopIteration        self.index -= 1        return self.text[self.index] print("".join(Reverse("python")))
Output
nohtyp

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Generator expression of squares

Generator expression of squares

EasyIterator & Generator Programs · 6 of 20

Write a Python program that sums squares with a generator expression.

Output
generator
385
0

Approach

  1. Round brackets create a lazy generator.

Solution

Python
squares = (n * n for n in range(1, 11))print(type(squares).__name__)print(sum(squares))print(sum(squares))
Output
generator
385
0

Line by line

Line 4

The generator is used up after the first sum, so the second sum is 0.

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs