Python Tricks
18. map(func, iter)
Executes the function func on all elements of the iterable iter.
1 | >>> list(map(lambda x: x[0], ['red', 'green', 'blue'])) |
17. map(func, i1, …, ik)
Executes the function func on all k elements of the k iterables.
1 | >>> list(map(lambda x,y: str(x) + ' ' + y + 's', [0, 2, 3], ['apple', 'orange', 'banana'])) |
16. string.join(iter)
Concatenates iterable elements iter separated by string.
1 | >>> ' marries '.join(list(['Alice', 'Bob'])) |
15. filter(function, iterable)
Filters out elements in iterable for which function returns False (or 0).
1 | >>> list(filter(lambda x: True if x > 17 else False, [1, 15, 17, 18, 19])) |
14. string.strip()
Removes leading and trailing whitespaces of string.
1 | >>> print(" \n \t 42 \t ".strip()) |
13. sorted(iter)
Sorts iterable iter in ascending order.
1 | >>> sorted([8, 3, 2, 42, 5]) |
12. sorted(iter, key=key)
Sorts according to the key function in ascending order.
1 | >>> sorted([8, 3, 2, 42, 5], key=lambda x: 0 if x==42 else x) |
11. help(func)
Returns documentation of func.
1 | >>> help(str.upper) |
10. zip(i1, i2, …)
Groups the k-th elements of iterators i1, i2, … together.
1 | >>> list(zip(['Alice', 'Anna'], ['Bob', 'Jon', 'Frank'], ['Jason', 'Mike'])) |
9. Unzip
Equal to: 1) unpack the zipped list, 2) zip the result.
1 | >>> list(zip(*[('Alice', 'Bob', 'Jason'), ('Anna', 'Jon', 'Mike')])) |
8. enumerate(iter)
Assigns a counter value to each element of the iterable iter.
1 | >>> list(enumerate(['Alice', 'Bob', 'Jon'])) |
7. Start a web server
Want to share files between PC and phone? Run this command in PC’s shell.
is any port number 0–65535. Type
: in the phone’s browser. You can now browse the files in the PC directory.
1 | python3 -m http.server <Port> |
6. Read comic
Open the comic series xkcd in your web browser.
1 | import antigravity |
5. Zen of Python
Get valuable advice of how to write Pythonic code.
1 | import this |
4. Swapping numbers
Swapping variables is a breeze in Python. No offense, Java!
1 | >>> a, b = 'Jane', 'Alice' |
3. Unpacking arguments
Use a sequence as function arguments via asterisk operator *. Use a dictionary (key, value) via double asterisk operator **.
1 | >>> def f(x, y, z): |
2. Extended Unpacking
Use unpacking for multiple assignment feature in Python.
1 | >>> a, *b = [1, 2, 3, 4, 5] |
1. Merge two dictionaries
Use unpacking to merge two dictionaries into a single one.
1 | >>> x = {'Alice': 18} |