Python Tips – Basic but extremely useful
- Home
- Python Tips – Basic but extremely useful
Python is celebrated for its readability and clean syntax. However, even experienced developers sometimes overlook built-in features and idioms that can make code significantly more Pythonic, efficient, and concise.
Whether you are building a full-stack application or writing data scripts, here are some fundamental yet incredibly useful Python tips that will level up your coding game.
Instead of accessing elements by index, Python allows you to unpack tuples, lists, and other iterables directly into variables in a single, readable line.
# Instead of this:
coordinates = (10, 20)
x = coordinates[0]
y = coordinates[1]
# Do this:
x, y = (10, 20)
You can even use the asterisk (*) to capture excess or variable-length items:
first, *middle, last = [1, 2, 3, 4, 5]
print(middle) # Output: [2, 3, 4]
range(len()) for enumerate()Looping through a sequence while needing its index using range(len()) is considered non-Pythonic. Instead, use enumerate(), which yields both the index and the value simultaneously.
# Non-Pythonic
colors = ["red", "green", "blue"]
for i in range(len(colors)):
print(i, colors[i])
# Pythonic
for i, color in enumerate(colors):
print(i, color)
join()Using the + operator inside loops to concatenate strings creates a new string object every time, which degrades performance due to string immutability. Using .join() is much faster, cleaner, and memory-efficient.
# Inefficient
words = ["Python", "is", "awesome"]
sentence = ""
for word in words:
sentence += word + " "
# Efficient
sentence = " ".join(words)
Introduced in Python 3.6, formatted string literals (f-strings) allow you to embed expressions inside string literals using curly braces {}. They are faster, more readable, and less error-prone than legacy %-formatting or .format().
name = "Alice"
score = 95
print(f"Hello, {name}! Your score is {score}%.")
zip()When you need to iterate through two or more lists in parallel, zip() pairs corresponding elements together cleanly without messy index management.
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
.get()Accessing a missing key in a dictionary using standard bracket notation (dict['key']) raises a KeyError and can crash your program. Using .get() allows you to provide a default fallback value safely.
user = {"name": "Bob"}
# Avoids KeyError and returns "Guest" if "role" doesn't exist
role = user.get("role", "Guest")
print(role) # Output: Guest
Writing great Python code isn’t just about making it work; it’s about writing code that is clean, readable, and idiomatic. By incorporating these fundamental tips into your daily workflow, you’ll write more robust code with fewer bugs.