11 Essential Pythonic Tricks to Write Cleaner, Faster Code
Discover 11 practical Pythonic techniques—from unpacking assignments and using zip to lambda functions, list comprehensions, placeholder passes, regex, map/reduce, and more—that enhance code readability, efficiency, and elegance, each illustrated with clear examples you can apply immediately.
If you can use Python in a Pythonic way, Python is an elegant language.
Regardless of experience, writing real Python code takes time. This article shares 11 Pythonic tricks to boost your Python skills.
1. Destructuring Assignment in Python
Assigning variables is a basic operation; Python provides syntactic sugar to make it more elegant.
a, *mid, b = [1, 2, 3, 4, 5, 6]
print(a, mid, b) # 1 [2, 3, 4, 5] 6With the star, mid captures the middle items as a list.
2. Using the zip Function to Aggregate Items
The built‑in zip function aggregates elements from multiple iterables (lists, tuples, sets) and returns an iterator.
ids = [1, 2, 3, 4]
leaders = ['Elon Musk', 'Tim Cook', 'Bill Gates', 'Yang Zhou']
sex = ['male', 'male', 'male', 'male']
record = zip(ids, leaders, sex)
print(list(record))
# [(1, 'Elon Musk', 'male'), (2, 'Tim Cook', 'male'), (3, 'Bill Gates', 'male'), (4, 'Yang Zhou', 'male')]3. Proper Use of Lambda Functions
Lambda functions are handy for one‑liners. Example: print all odd numbers from a list.
numbers = [1, 37, 43, 51, 83, 43]
print(list(filter(lambda x: x % 2 == 1, numbers)))
# [1, 37, 43, 51, 83, 43]4. Ignoring Variables with an Underscore
When a variable is unused, you can ignore it with an underscore.
L = [1, 3, 5, 7]
a, _, b, _ = L
print(a, b) # 1 55. Harnessing List Comprehensions
List comprehensions condense multiple operations into a single line.
Genius = ["Jerry", "Jack", "tom", "yang"]
L1 = [name if name.startswith('y') else 'Not Genius' for name in Genius]
print(L1)
# ['Not Genius', 'Not Genius', 'Not Genius', 'yang']6. Placing a Placeholder
When a function’s implementation is pending, use pass or an ellipsis as a placeholder.
def my_func():
pass
# or
def my_func():
...7. Processing Text with Regular Expressions
The re module provides full regex support.
import re
txt = "Yang is so handsome!!!"
result = re.search("Elon", txt)
print(result) # None8. map and reduce in Python
mapapplies a function to each element of an iterable, returning a new iterator.
names = ['yAnG', 'MASk', 'thoMas', 'LISA']
names = map(str.capitalize, names)
print(list(names))
# ['Yang', 'Mask', 'Thomas', 'Lisa'] reducecumulatively applies a two‑argument function to the items of an iterable.
from functools import reduce
city = ['L', 'o', 'n', 'd', 'o', 'n', 2, 0, 2, 0]
city_str = reduce(lambda x, y: str(x) + str(y), city)
print(city_str) # London20209. Elegantly Removing Unnecessary Spaces
Combine split() and join() to normalize whitespace.
quote = " Yang is a full stack hacker."
new_quote = ' '.join(quote.split())
print(new_quote)
# Yang is a full stack hacker.10. The Simplest Way to Shallow‑Copy a List
a = [1, 2, 3, 4, 5, 6]
b = a[:]
b[0] = 100
print(b) # [100, 2, 3, 4, 5, 6]
print(a) # [1, 2, 3, 4, 5, 6]11. Checking the Last Expression Value in the Interpreter
Use an underscore to retrieve the result of the most recent expression.
>> 5 + 6
11
>>> _
11These 11 Pythonic tricks aim to make your code cleaner, more concise, and more Python‑idiomatic.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
