2.12 itertools#

Important

This lesson is still under development.

import itertools

combinations#

x = [1,2,3]
print([x for x in itertools.combinations(x, 2)])
[(1, 2), (1, 3), (2, 3)]
print([x for x in itertools.combinations(x, 3)])
[(1, 2, 3)]
print([x for x in itertools.combinations(x, 10)])
[]

product#

for prod in (itertools.product([1, 2], [11, 12])):
    print(prod)
(1, 11)
(1, 12)
(2, 11)
(2, 12)
for prod in (itertools.product([1,2,3], [11, 12, 13])):
    print(prod)
(1, 11)
(1, 12)
(1, 13)
(2, 11)
(2, 12)
(2, 13)
(3, 11)
(3, 12)
(3, 13)
for prod in (itertools.product([1, 2], [11, 12], [21, 23])):
    print(prod)
(1, 11, 21)
(1, 11, 23)
(1, 12, 21)
(1, 12, 23)
(2, 11, 21)
(2, 11, 23)
(2, 12, 21)
(2, 12, 23)

permutations#

print([x for x in itertools.permutations([1,2,3])])
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
print([x for x in itertools.permutations([1,2,3], 2)])
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

repeat#

Repeats a value n times

value = 10
n = 4

rep = itertools.repeat(value, n)
print(rep)
repeat(10, 4)
print(type(rep))
<class 'itertools.repeat'>
for val in rep:
    print(val)
10
10
10
10

Total running time of the script: ( 0 minutes 0.005 seconds)

Gallery generated by Sphinx-Gallery