13 Python Tricks to Write Cleaner, Faster Code
This article presents a collection of practical Python tips—from concise imports and the handy '_' placeholder to efficient string joining, powerful uses of zip(), elegant swapping, enumeration, multi‑exception handling, list chunking, and clean file handling—helping developers write more readable and performant code.
Sometimes you see cool Python code that amazes you with its simplicity and elegance; such code relies on Pythonic techniques that, once mastered, let you write code that reads like poetry.
1. Import Modules
Long import statements can become cumbersome as projects grow. You can shorten them, but beware of name clashes.
import urllib.request
url = r'http://www.landsblog.com'
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)Or using a shorter alias:
from urllib import request
url = r'http://www.landsblog.com'
req = request.Request(url)
response = request.urlopen(req)When module names are long, you can alias specific functions:
from bs4 import BeautifulSoup as BS
html = '''
<html>
......
</html>
'''
soup = BS(html)2. The "_" Variable
In the interactive interpreter, the underscore stores the result of the last expression, allowing you to reuse it without assigning a name.
>> 1 + 1
2
>>> _
23. Merging Strings
Using the "+" operator creates many intermediate strings and wastes memory. Prefer ''.join() for efficiency.
# Bad
string = ['a','b','c','d','e','f','g','h']
def fun(string):
all_string = ''
for i in string:
all_string += i
return all_string
# Good
string = ['a','b','c','d','e','f','g','h']
def fun(string):
return ''.join(string)4. Powerful zip()
zip()can simplify many tasks.
# Matrix transpose
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
re_a = list(zip(*a))
# => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
# Swap dict keys and values
a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
new_dict = dict(zip(a.values(), a.keys()))
# Merge adjacent list items
a = [1, 2, 3, 4, 5, 6]
list(zip(a[::2], a[1::2]))
# => [(1, 2), (3, 4), (5, 6)]5. Variable Swapping
# Traditional
tmp = a
a = b
b = tmp
# Pythonic
a, b = b, a6. Getting Index in a Loop
a = [8, 23, 45, 12, 78]
for index, value in enumerate(a):
print(index, value)7. Catch Multiple Exceptions in One Line
try:
pass
except (ExceptionA, ExceptionB, ...) as e:
pass8. Split a List into Equal‑Sized Chunks
a = [1, 2, 3, 4, 5, 6]
list(zip(*[iter(a)]*2))
# => [(1, 2), (3, 4), (5, 6)]9. Find an Element’s Index
a = ['a', 'b', 'c', 'd', 'e', 'f']
a_i = a.index('a')
# => 010. Reverse a String Quickly
# Using list reverse
s = 'Python is a powerful language.'
lst = list(s)
lst.reverse()
rev = ''.join(lst)
# Using slicing
rev = s[::-1]11. Numeric Comparison
x = 2
if 1 < x < 3:
print(x) # 2
if 1 < x > 0:
print(x) # 212. Elegant File Opening
Use a with statement to automatically close files.
with open('nothing.txt', 'r') as f:
f.read()13. Say Goodbye to Your Memory
crash = dict(zip(range(10**0xA), range(10**0xA)))This creates an enormous dictionary that quickly exhausts memory.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
