from itertools import count# infinite countingfor i in count(10, 2): print(i) if i > 20: break#ans: 10, 12, 14, 16, 18, 20
from itertools import cycle# infinite cyclingcolors = ['red', 'green', 'blue']color_cycle = cycle(colors)for i, color in enumerate(color_cycle): print(color) if i >= 5: break#ans: red, green, blue, red, green, blue
from itertools import repeat# repeat valuelist(repeat(10, 3))#ans: [10, 10, 10]
from itertools import chain# combine iterableslist(chain([1, 2], [3, 4], [5, 6]))#ans: [1, 2, 3, 4, 5, 6]
from itertools import islice# slice iteratorlist(islice(range(10), 2, 8, 2))#ans: [2, 4, 6]#ans: take first nlist(islice(count(), 5))#ans: [0, 1, 2, 3, 4]
from itertools import product# cartesian productlist(product([1, 2], ['a', 'b']))#ans: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
from itertools import permutations# all orderingslist(permutations([1, 2, 3], 2))#ans: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
from itertools import combinations# unique selectionslist(combinations([1, 2, 3, 4], 2))#ans: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
from itertools import count# count is infinite?c = count()next(c)#ans: 0next(c)#ans: 1#ans: never stops
from itertools import cycle# cycle repeats?c = cycle([1, 2])[next(c) for _ in range(5)]#ans: [1, 2, 1, 2, 1]
from itertools import repeat# repeat without count?r = repeat(5)#ans: infinitelist(islice(r, 3))#ans: [5, 5, 5]
from itertools import chain# chain vs +?chain([1], [2], [3])#ans: iterator[1] + [2] + [3]#ans: [1, 2, 3] (list)
from itertools import islice# islice with step?list(islice(range(20), 0, 10, 2))#ans: [0, 2, 4, 6, 8]
from itertools import product# product with repeat?list(product([0, 1], repeat=3))#ans: [(0,0,0), (0,0,1), (0,1,0), (0,1,1),#ans: (1,0,0), (1,0,1), (1,1,0), (1,1,1)]
from itertools import permutations# permutations vs combinations?list(permutations([1, 2], 2))#ans: [(1, 2), (2, 1)]list(combinations([1, 2], 2))#ans: [(1, 2)]
from itertools import combinations# combinations order?list(combinations([3, 1, 2], 2))#ans: [(3, 1), (3, 2), (1, 2)]#ans: maintains input order
from itertools import groupby# group consecutivedata = [1, 1, 2, 2, 2, 3][(k, list(g)) for k, g in groupby(data)]#ans: [(1, [1, 1]), (2, [2, 2, 2]), (3, [3])]
from itertools import zip_longest# zip with fillvaluelist(zip_longest([1, 2], ['a', 'b', 'c'], fillvalue=0))#ans: [(1, 'a'), (2, 'b'), (0, 'c')]
Google tag (gtag.js)