On this page
itertools.pairwise
Prev: itertools.islice | Up: itertools | Next: itertools.permutations
Rel: itertools.accumulate, itertools.batched, itertools.chain, itertools.combinations
Ref: docs.python.org — itertools.pairwise
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import pairwise
Signature & Overview
itertools.pairwise(iterable, /)
Return an iterator of overlapping pairs taken from the input iterator.
Usage
from itertools import pairwise
assert list(pairwise([10, 20, 35, 50])) == [(10, 20), (20, 35), (35, 50)]
# Great for computing deltas
deltas = [b - a for a, b in pairwise([10, 20, 35, 50])]
assert deltas == [10, 15, 15]
Gotchas
- Empty for 0 or 1 elements:
list(pairwise([42]))returns[]without error. - Fixed window size of 2: For wider sliding windows, use a
deque(maxlen=k)helper.
REPL Inspect
from itertools import pairwise
help(pairwise)
Linked from
Related notes
- tuts/python3/stdlib_module/itertools/islice Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/permutations Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/compress shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/count shared tags: #itertools, #stdlib