10 Hidden Python Features That Can Supercharge Your Code
Discover ten powerful yet often overlooked Python features—from the walrus operator and generators to dataclasses and f‑strings—that can dramatically simplify code, boost performance, and enhance readability for developers of all levels.
1. Walrus Operator (:=) – Assignment Within Expressions
The walrus operator ( := ) was introduced in Python 3.8 and allows assignment inside an expression.
Before the walrus operator, you would typically write:
<code>data = input("请输入一些内容:")
if len(data) > 5:
print("输入过长!")
</code>With the walrus operator, the code can be simplified to:
<code>if (data := input("请输入一些内容:")) and len(data) > 5:
print("输入过长!")
</code>It reduces duplicated code and improves readability of loops and conditionals.
2. Generators – Efficient Data Stream Processing
Generators enable lazy evaluation , allowing efficient handling of large data sets.
Before using generators, a list comprehension would consume a lot of memory:
<code>nums = [x**2 for x in range(1000000)]
</code>Using a generator, the code becomes:
<code>nums = (x**2 for x in range(1000000))
</code>Generators generate values on demand, saving memory and are ideal for large datasets.
3. else Block in Loops – Unexpectedly Powerful
Python allows an else block after for and while loops, which executes only if the loop wasn’t terminated by break .
<code>for num in range(2, 10):
for i in range(2, num):
if num % i == 0:
break
else:
print(num, "是质数")
</code>This provides a clean way to check whether a loop completed fully, useful in search algorithms.
4. collections.defaultdict – No More Key Errors
Unlike a regular dict , defaultdict automatically initializes missing keys, avoiding KeyError exceptions.
Before defaultdict :
<code>counts = {}
counts["apple"] += 1
</code>After using defaultdict :
<code>from collections import defaultdict
counts = defaultdict(int)
counts["apple"] += 1
</code>This eliminates unnecessary condition checks and simplifies counting operations.
5. Function Argument Unpacking ( *args and **kwargs )
Python allows dynamic unpacking of function arguments, enabling you to pass any number of positional or keyword arguments.
<code>def greet(*names, greeting="Hello"):
for name in names:
print(f"{greeting}, {name}!")
greet("John", "David", "Sam", greeting="Hi")
</code>This provides flexible function calls and simplifies handling of variable arguments.
6. List Comprehensions – More Than Just Lists!
Most developers know list comprehensions, but you can also use set and dictionary comprehensions.
<code>squares = {x: x**2 for x in range(5)}
unique_numbers = {x for x in [1, 2, 2, 3, 4]}
</code>They are more concise and faster than explicit loops for creating lists, sets, and dictionaries.
7. @property Decorator – Cleaner Accessors and Mutators
The @property decorator lets you define read‑only attributes, making code more Pythonic and readable.
Before using @property :
<code>class Person:
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
p = Person(name="Aashish")
p.get_name()
</code>After applying @property :
<code>class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
p = Person(name="Aashish")
p.name
</code>This removes the need for explicit getter methods.
8. itertools – Infinite and Efficient Iteration
The itertools module provides powerful iteration tools.
<code>from itertools import cycle
colors = cycle(["red", "blue", "green"])
for _ in range(5):
print(next(colors))
</code>It efficiently handles large or infinite sequences, ideal for loops, permutations, and combinations.
9. F‑Strings – The Ultimate String Formatting Tool
F‑strings ( f"" ) are faster and more concise than .format() or % formatting.
<code>name = "Aashish"
age = 25
print(f"My name is {name} and I am {age} years old.")
</code>They are more readable and execute faster.
10. dataclasses – Auto‑Generated Boilerplate
The dataclass decorator creates lightweight classes without manually writing __init__ , __repr__ , and other methods.
Before using dataclass :
<code>class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
def __repr__(self):
return f"Car({self.brand}, {self.year})"
</code>After applying dataclass :
<code>from dataclasses import dataclass
@dataclass
class Car:
brand: str
year: int
c = Car(brand="xyz", year=2025)
</code>Conclusion
Python has many "hidden gems" that may seem confusing at first, but once mastered, they greatly improve efficiency and readability.
Which of these features surprised you the most? Feel free to share your thoughts in the comments!
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
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.