itertools.combinations(itr, r)
-
The
combinationsfunction is used to:- Cycle through each element of an iterable
- Return
rlength subsequences of elements
- This iterable is based on the
itrparameter - The length of subsequences is based on the
rparameter combinationsreturns an iterator ofrlength subsequences of elements from the iterableitr
Illustrating the combinations Function
>>> from itertools import combinations
>>> itr = combinations('ABC', 2)
>>> for i in itr: print(i)
('A', 'B')
('A', 'C')
('B', 'C')
>>> itr = combinations(range(4))
>>> for i in itr: print(i)
(0, 1, 2)
(0, 1, 3)
(0, 2, 3)
(1, 2, 3)
>>> from itertools import combinations_with_replacement
>>> itr = combinations_with_replacement('ABC', 2)
>>> for i in itr: print(i)
('A', 'A')
('A', 'B')
('A', 'C')
('B', 'B')
('B', 'C')
('C', 'C')References
Previous