Dup Ver Goto 📝

5 Useful Iterator Functions

To
86 lines, 281 words, 2035 chars Page '5_Useful_Iterator_Functions' does not exist.

Notes from this Indently video:

batched

from itertools import batched

numbers: list[int] = [1,2,3,4,5,6,7]
my_batch: batched = batched(numbers,n=3)

# don't actually convert to a list unless needed
print(list(my_batch))
# [(1, 2, 3), (4, 5, 6), (7,)]

batched_help == """
batched(iterable, n)

Batch data into tuples of length n. The last batch may be shorter than n.
"""

zip_longest

from itertools import zip_longest

a = [ "a", "b", "c" ]
x = [ "x", "y" ]
u = [ "u", "v", "w", "t" ]

print(list(zip(a,x,u)))
# [('a', 'x', 'u'), ('b', 'y', 'v')]

print(list(zip_longest(a,x,u)))
# [('a', 'x', 'u'), ('b', 'y', 'v'), ('c', None, 'w'), (None, None, 't')]

print(list(zip_longest(a,x,u,fillvalue="XYZ")))
# [('a', 'x', 'u'), ('b', 'y', 'v'), ('c', 'XYZ', 'w'), ('XYZ', 'XYZ', 't')]

product

Cartesian product.

from itertools import product

print(list(product(["a","b"],["c","d"])))
# [('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]

print(["".join(x) for x in list(product(["a","b"],repeat=3))])
# ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']

starmap

Saves doing a lambda x: f(*x) wrapper.

from itertools import starmap

def get_sum(a:int, b:int, c:int) -> int:
    return sum((a,b,c))

data: list[tuple[int,int,int]] = [(1,2,3), (4,5,6)]
sums: starmap = starmap(get_sum, data)

# star as in * when passing args

data: list[tuple[int,int]] = [(2,4), (3,3), (4,2)]
sums: starmap = starmap(pow, data)

groupby

from itertools import groupby

def count_vowels(text) -> int:
    # not an efficient way to do this
    return len([x for x in text if x.lower() in "aeiou"])

words: list[str] = ['cat', 'dog', 'mr', 'flibble', 'hex', 'vision']
sorted_words: list[str] = sorted(words, key=count_vowels)
grouped: groupby = groupby(sorted_words, key=count_vowels)

for vowels, grouped_words in grouped:
    print(vowels, list(grouped_words))
# 0 ['mr']
# 1 ['cat', 'dog', 'hex']
# 2 ['flibble']
# 3 ['vision']