13 Little‑Known Python Tricks to Write Cleaner, More Efficient Code
Discover 13 practical Python techniques—from simultaneous variable assignment and tuple swapping to list and dictionary comprehensions, defaultdict, enumerate, slicing, zip, join, lambda functions, itertools, Counter, and f‑strings—that help you write cleaner, more efficient, and more maintainable code.
13 Python Tricks You Probably Didn't Know
As a developer with ten years of programming experience, I share thirteen useful Python tricks that can make your code more concise, elegant, and efficient.
1. Assign Multiple Variables in One Line
Python allows simultaneous assignment of several variables, reducing boilerplate.
<code>a, b, c = 1, 2, 3
print(a, b, c) # 输出:1 2 3</code>2. Swap Variable Values Without a Temporary Variable
Tuple unpacking lets you exchange two variables in a single statement.
<code>a, b = 1, 2
a, b = b, a # 交换
print(a, b) # 输出:2 1</code>3. List Comprehensions
Generate lists compactly with a single expression.
<code>squares = [x**2 for x in range(10)]
print(squares) # 输出:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</code>4. Dictionary Comprehensions
Create dictionaries directly from an expression.
<code>squared_dict = {x: x**2 for x in range(5)}
print(squared_dict) # 输出:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}</code>5. defaultdict
Automatically provides a default value for missing keys.
<code>from collections import defaultdict
d = defaultdict(int)
d['a'] += 1
print(d['a']) # 输出:1</code>6. enumerate for Index‑Value Pairs
Iterate over a list while accessing both index and element.
<code>my_list = ['a', 'b', 'c']
for index, value in enumerate(my_list):
print(f'Index: {index}, Value: {value}')
# 输出:
# Index: 0, Value: a
# Index: 1, Value: b
# Index: 2, Value: c</code>7. Slicing
Extract sub‑sequences from lists, strings, or tuples.
<code>my_list = [1, 2, 3, 4, 5, 6]
sub_list = my_list[2:5] # 从索引2到4
print(sub_list) # 输出:[3, 4, 5]</code>8. zip for Parallel Iteration
Iterate over multiple iterables in lockstep.
<code>names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f'{name} is {age} years old')
# 输出:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old</code>9. join for Efficient String Concatenation
Use the built‑in join method instead of repeated + operations.
<code>words = ['Python', 'is', 'awesome']
sentence = ' '.join(words)
print(sentence) # 输出:Python is awesome</code>10. Lambda Functions
Define small anonymous functions in a single line.
<code>multiply = lambda x, y: x * y
print(multiply(2, 3)) # 输出:6</code>11. itertools for Infinite Iteration
The itertools module provides fast iterators, such as an infinite counter.
<code>import itertools
counter = itertools.count(start=10, step=5)
for _ in range(5):
print(next(counter)) # 输出:10 15 20 25 30</code>12. collections.Counter for Counting Elements
Quickly tally occurrences of items in an iterable.
<code>from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
count = Counter(my_list)
print(count) # 输出:Counter({'banana': 3, 'apple': 2, 'orange': 1})</code>13. f‑strings for Easy String Formatting
Python 3.6+ f‑strings simplify interpolation compared to format .
<code>name = 'Alice'
age = 25
message = f'Hello, my name is {name} and I am {age} years old.'
print(message) # 输出:Hello, my name is Alice and I am 25 years old.</code>Practice these tricks regularly, keep your code concise, and refer to the official Python documentation whenever you encounter unfamiliar concepts.
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.