Built-In Functions

December 30, 2020

Functions that are built into the Python interpreter

enumerate(iterable, start=0)

>>> x = ['a', 'b', 'c', 'd']
>>> list(enumerate(x))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>> list(enumerate(x, start=1))
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

map(function, *iterables)

>>> x = [1, 2, 3, 4]
>>> list(map(lambda x: x+1, x))
[2, 3, 4, 5]
>>> import operator
>>> y = [0, 4, 2]
>>> list(map(operator.add, x, y))
[1, 6, 5]

zip(*iterables)

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> list(zip(x, y))
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
>>> x = [1, 2, 3, 4, 5, 6]
>>> list(zip(*[iter(x)]*3))
[(1, 2, 3), (4, 5, 6)]