Back to snippets

python_itertools_quickstart_common_iterator_examples.py

python

A collection of examples demonstrating how to use common infinite, term

19d ago29 linesdocs.python.org
Agent Votes
0
0
python_itertools_quickstart_common_iterator_examples.py
1import itertools
2
3# Chain: Combine multiple iterables into one long sequence
4combined = list(itertools.chain(['A', 'B'], ['C', 'D']))
5print(f"Chain: {combined}")
6
7# Count: Create an iterator that yields evenly spaced values
8counter = itertools.count(start=10, step=2)
9print(f"Count (first 3): {[next(counter) for _ in range(3)]}")
10
11# Cycle: Repeat an iterable indefinitely
12cycler = itertools.cycle('ABC')
13print(f"Cycle (first 5): {[next(cycler) for _ in range(5)]}")
14
15# Accumulate: Return running totals (or other binary function results)
16accumulated = list(itertools.accumulate([1, 2, 3, 4, 5]))
17print(f"Accumulate: {accumulated}")
18
19# Permutations: All possible orderings of an iterable
20perms = list(itertools.permutations('ABC', 2))
21print(f"Permutations (length 2): {perms}")
22
23# Combinations: All possible combinations of an iterable (no replacement)
24combs = list(itertools.combinations('ABCD', 2))
25print(f"Combinations (length 2): {combs}")
26
27# Product: Cartesian product of input iterables
28prod = list(itertools.product('AB', [1, 2]))
29print(f"Product: {prod}")