17 May 2023
→ Iterators are fast and memory-efficient
→ Can be used with lists, tuples, dictionaries, sets, etc.
→ Can be finite or infinite
count(start, step)Starts from the start and goes infinitely
for i in intertools.count(5, 5):
if i == 20:
break
else:
print(i, end=" ")
# Output: 5, 10, 15
cycle(iterable)count = 0
for i in intertools.cycle('AB'):
if count > 7:
break
else:
print(i, end=" ")
count += 1
# Output: A B A B A B A B
repeat(val, num)Repeatedly runs an infinite number of times. If optional num is provided, it runes num number of times.
print(list(itertools.repeat(25, 4)))
# Output: [25, 25, 25, 25]
product()Computes the cartesian product on input iterables.
→ Use the optional repeat keyword to compute the product of an iterable with itself.
list(product([1,2], repeat=2))
# Output: [(1, 1), (1, 2), (2, 1), (2, 2)]
list(product(['hello', 'world'], '2'))
# Output: [('hello, '2'), ('world', '2')]
permutations()Generates all possible permutations of an iterable.
→ Optional argument group_size becomes length of the iterable if not specified.
list(permutations([1, 'hello'], 2))
# Output [(1, 'hello'), ('hello', 1)]
chain()Chains iterables one after another.
li1 = [1, 2, 3, 4]
li2 = [5, 6, 7, 8]
list(intertools.chain(li1, li2))
# Output: [1, 2, 3, 4, 5, 6, 7, 8]
filterfalse()Only returns values that return false for the passed function.
li = [2, 4, 5, 7]
list(itertools.filterfalse(lambda x : x % 2 == 0, li))
# Output: [5, 7]
takewhile()Returns values until the function returns false for the first time. The opposite of takewhile() is dropwhile().
li = [2, 4, 6, 7]
list(itertools.takewhile(lambda x : x % 2 == 0, li))
# Output: [2, 4, 6]