CheatSheet Python 5 Functions and Tricks
CheatSheet Python 5 Functions and Tricks
A map(func, iter) Executes the function on all elements of list(map(lambda x: x[0], ['red', ['r', 'g', 'b']
D the iterable 'green', 'blue']))
V
A map(func, i1, ..., Executes the function on all k elements of list(map(lambda x, y: str(x) + ' ' + ['0 apples', '2
ik) the k iterables y + 's' , [0, 2, 2], ['apple', oranges', '2
N
C 'orange', 'banana'])) bananas']
E
string.join(iter) Concatenates iterable elements ' marries '.join(list(['Alice', 'Alice marries Bob'
D separated by string 'Bob']))
F filter(func, Filters out elements in iterable for which list(filter(lambda x: True if x>17 [18]
U iterable) function returns False (or 0) else False, [1, 15, 17, 18]))
N
C string.strip() Removes leading and trailing print(" \n \t 42 \t ".strip()) 42
T whitespaces of string
I
O sorted(iter) Sorts iterable in ascending order sorted([8, 3, 2, 42, 5]) [2, 3, 5, 8, 42]
N
sorted(iter, Sorts according to the key function in sorted([8, 3, 2 , 42, 5], key=lambda [42, 2, 3, 5, 8]
S
key=key) ascending order x: 0 if x==42 e lse x)
zip(i1, i2, ...) Groups the i-th elements of iterators i1, i2, list(zip(['Alice', 'Anna'], ['Bob', [('Alice', 'Bob'),
… together 'Jon', 'Frank'])) ('Anna', 'Jon')]
Unzip Equal to: 1) unpack the zipped list, 2) zip list(zip(*[('Alice', 'Bob'), [('Alice', 'Anna'),
the result ('Anna', 'Jon')] ('Bob', 'Jon')]
enumerate(iter) Assigns a counter value to each element list(enumerate(['Alice', 'Bob', [(0, 'Alice'), (1,
of the iterable 'Jon'])) 'Bob'), (2, 'Jon')]
T python -m http.server Share files between PC and phone? Run command in PC’s shell. <P> is any port number 0–65535. Type < IP address of
R <P> PC>:<P> in the phone’s browser. You can now browse the files in the PC directory.
I
C Read comic import antigravity Open the comic series xkcd in your web browser
K
S
Zen of Python import this '...Beautiful is better than ugly. Explicit is ...'
Unpacking arguments Use a sequence as function arguments def f(x, y, z): return x + y * z
via asterisk operator *. Use a dictionary f(*[1, 3, 4]) 13
(key, value) via double asterisk operator ** f(**{'z' : 4, 'x' : 1, 'y' : 3
}) 13
Extended Unpacking Use unpacking for multiple assignment a, *b = [1, 2, 3, 4, 5] a = 1
feature in Python b = [2, 3, 4, 5]
Merge two dictionaries Use unpacking to merge two dictionaries x={'Alice' : 18} z = {'Alice': 18,
into a single one y={'Bob' : 27, 'Ann' : 22} 'Bob': 27, 'Ann': 22}
z = {**x,**y}