What are the coolest Python tricks? I’ve compiled this list of the best Python tricks—in reverse order. Without further ado, let’s dive into those crazy one-liner Python features, tricks, and functions:
18. Modifying Iterable Elements 1/2
The function map(func, iter)
executes the function func
on all elements of the iterable iter
.
list(map(lambda x: x[0], ['red', 'green', 'blue'])) # ['r', 'g', 'b']
Related article: Which is Faster — List Comprehension or the Map Function in Python
17. Modifying Iterable Elements 2/2
The function call map(func, i1, ..., ik)
executes the function func
on all k
elements of the k
iterables.
list(map(lambda x, y: str(x) + ' ' + y + 's' , [0, 2, 2], ['apple', 'orange', 'banana'])) # ['0 apples', '2 oranges', '2 bananas']
Related article: How to Get Rid of Python’s Map Function
16. Transform Iterables to Strings
The function call string.join(iter)
concatenates all elements in an iterable iter
separated by string
.
' marries '.join(list(['Alice', 'Bob'])) # 'Alice marries Bob'
Related article: How to Print a Python List Beautifully
15. Filtering Iterables
The function call filter(function, iterable)
filters out elements in iterable
for which function
returns False
(or 0).
list(filter(lambda x: True if x>17 else False, [1, 15, 17, 18])) # [18]
Related article: How to Filter in Python
14. Trim Strings
The function call string.strip()
removes leading and trailing whitespaces from string
.
print(" \n \t 42 \t ".strip()) # 42
Related article: Python Trim String [Ultimate Guide]
13. Basic Sorting
The built-in function call sorted(iter)
sorts iterable iter
in ascending order.
sorted([8, 3, 2, 42, 5]) # [2, 3, 5, 8, 42]
Related article: Python List Sort [Ultimate Guide]
12. Custom Sorting
The built-in function call sorted(iter, key=func)
sorts according to the key function func
in ascending order.
sorted([8, 3, 2, 42, 5], key=lambda x: 0 if x==42 else x) # [42, 2, 3, 5, 8]
Related article: Sorting with the Key Argument in Python
11. Help
The function call help(func)
returns documentation of func
.
help(str.upper) # '... to uppercase.'
Related: Become a Python master — and Join Our Community of Tens of Thousands of Ambitious Python Coders!
10. Zip
The function call zip(i1, i2, ...)
groups the k-th elements of iterators i1, i2
, … together.
list(zip(['Alice', 'Anna'], ['Bob', 'Jon', 'Frank'])) # [('Alice', 'Bob'), ('Anna', 'Jon')]
Related article: Zip Function in Python
9. Unzip
Equal to:
- unpack the zipped list, and
- zip the result.
list(zip(*[('Alice', 'Bob'), ('Anna', 'Jon')])) # [('Alice', 'Anna'), ('Bob', 'Jon')]
Related article: Unzip Function in Python
8. Smart Iteration
The function call enumerate(iter)
assigns a counter (index) value to each element of the iterable iter
.
list(enumerate(['Alice', 'Bob', 'Jon'])) # [(0, 'Alice'), (1, 'Bob'), (2, 'Jon')]
Related article: The Ultimate Guide to Python Lists
7. Start a Web Server
Want to share files between PC and phone? Run this command in PC’s shell. <P>
is any port number 0–65535. Type <IP address of PC>:<P>
in the phone’s browser. You can now browse the files in the PC directory.
python -m http.server <P>
Related article: Python One-Liner Webserver HTTP
6. Read Comic
Open the comic series xkcd in your web browser.
import antigravity
Related: Download Your Cheat Sheet “Python Tricks”
5. Zen of Python
Get valuable advice of how to write Pythonic code.
import this # '...Beautiful is better than ugly. Explicit is ...'
Related article: About Guido’s Article: “Fate of Reduce() in Python 3000”
4. Swapping Numbers
Swapping variables is a breeze in Python. No offense, Java!
a, b = 'Jane', 'Alice' a, b = b, a # a = 'Alice' # b = 'Jane'
Related article: Python Interview Questions
3. Unpacking Arguments
Use a sequence as function arguments via asterisk operator *.
Use a dictionary (key, value)
via double asterisk operator **
.
def f(x, y, z): return x + y * z f(*[1, 3, 4]) f(**{'z' : 4, 'x' : 1, 'y' : 3}) # 13 # 13
Related article: The Asterisk Operator in Python
2. Extended Unpacking
Use unpacking for multiple assignment feature in Python.
a, *b = [1, 2, 3, 4, 5] # a = 1 # b = [2, 3, 4, 5]
Related article: Python Slice Assignment
1. Merge Two Dictionaries
Use unpacking to merge two dictionaries into a single one.
x={'Alice' : 18} y={'Bob' : 27, 'Ann' : 22} z = {**x,**y} # z = {'Alice': 18, 'Bob': 27, 'Ann': 22}
Related article: Python Dictionary — The Ultimate Guide
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.