Python Tricks to Boost Your Productivity
Python is known for its simplicity and readability, but there are some lesser‑known features that can make your code even more elegant and efficient. Here are four practical tips to level up your Python skills.
1. Use enumerate() for Indexed Loops
Instead of managing a loop counter manually, let enumerate() do the work. It returns both the index and the value, keeping your code clean.
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
2. Leverage List Comprehensions
List comprehensions provide a concise way to create lists. They are often faster and more readable than traditional for loops.
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) # [0, 4, 16, 36, 64]
3. Safely Access Dictionaries with .get()
Accessing dictionary keys directly can raise a KeyError. Use .get() to provide a default value and avoid exceptions.
user = {
'name': 'Alice', 'age': 30}
city = user.get('city', 'Unknown')
print(city) # Unknown
4. Unpacking with * and **
The * operator unpacks iterables, while ** unpacks dictionaries. This is incredibly useful for function arguments and combining data.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
info = {
'name': 'Bob', 'age': 25}
greet(**info) # Equivalent to greet(name='Bob', age=25)
Start applying these tricks today and watch your Python code become cleaner and more Pythonic!