So, ā¦ because it is ātrivialā, and I can write it in one line, it need not be included??
10.12 Batteries Included
Python has a ābatteries includedā philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. [ā¦snip]
Letās look at itertools
for a second:
def chain(*iterables):
return (element for it in iterables for element in it)
chain_from_iterable = lambda iterables: (element for it in iterables for element in it)
def compress(data, selectors):
return (d for d, s in zip(data, selectors) if s)
def starmap(function, iterable):
return (function(*args) for args in iterable)
Those are one-liners which were turned into precompile functions bundled in the itertools
module. Why bother? We could easily write them ourselves.
The following are āone-linersā from the itertools recipes section:
def take(n, iterable):
return list(islice(iterable, n))
def prepend(value, iterator):
return chain([value], iterator)
def tabulate(function, start=0):
return map(function, count(start))
def tail(n, iterable):
return iter(collections.deque(iterable, maxlen=n))
def nth(iterable, n, default=None):
return next(islice(iterable, n, None), default)
def quantify(iterable, pred=bool):
return sum(map(pred, iterable))
def ncycles(iterable, n):
return chain.from_iterable(repeat(tuple(iterable), n))
def sumprod(vec1, vec2):
return sum(starmap(operator.mul, zip(vec1, vec2, strict=True)))
def sum_of_squares(it):
return sumprod(*tee(it))
def transpose(it):
return zip(*it, strict=True)
def matmul(m1, m2):
return batched(starmap(sumprod, product(m1, transpose(m2))), len(m2[0]))
def flatten(list_of_lists):
return chain.from_iterable(list_of_lists)
def triplewise(iterable):
return ((a, b, c) for (a, _), (b, c) in pairwise(pairwise(iterable)))
def unique_justseen(iterable, key=None):
return map(next, map(operator.itemgetter(1), groupby(iterable, key)))
def first_true(iterable, default=False, pred=None):
return next(filter(pred, iterable), default)
All of these are simple enough we can write them ourselves, yet theyāve been added to the recipe area and into more-itertools
. If āI have not had any need for a flat map functionā is the discriminator here, how did tabulate
get into the recipes? Iāve never had any need for it. So I think ānicheā and ātrivialā are not entry barriers here.