Python Tip of the Day — Learn Something New Daily
Python Tip of the Day
Welcome to the Python Tip of the Day — a daily series where you learn one short, powerful Python concept, trick, or best practice. Every tip is simple, practical, and beginner-friendly, with examples you can use immediately.
Tip 1 — Use enumerate() Instead of range(len())
When looping through a list, use enumerate() to get both index and value cleanly.
for i, item in enumerate(["a", "b", "c"], start=1):
print(i, item)
Why? Cleaner, more Pythonic, and avoids mistakes with indexing.
Tip 2 — Use List Comprehensions for Cleaner Loops
Instead of building lists with a for loop and .append(), use a list comprehension to keep your code short and Pythonic.
# Traditional way
squares = []
for x in range(10):
squares.append(x * x)
# List comprehension way
squares = [x * x for x in range(10)]
print(squares)
When to use: whenever you are creating a new list from another iterable (filtering, transforming, mapping).
Why it matters: list comprehensions are usually faster, shorter, and more readable than manual loops with .append().
Tip 3 — Swap Variables Without a Temporary Variable
Python allows you to swap variables in a single line, without using a temporary variable. This is clean, fast, and very useful in many logic-based problems.
a = 10
b = 5
# Swap values
a, b = b, a
print(a, b) # Output: 5 10
When to use: in algorithms, sorting, and anywhere you need quick value swaps.
Why it matters: shorter, cleaner, and avoids using extra memory compared to temp variables.
Tip 4 — Use set() for Fast Membership Checks
Checking if an item exists in a list is slow because lists use linear search.
Using a set() makes membership checks extremely fast (O(1) time).
items = [1, 2, 3, 4, 5]
lookup = set(items)
print(3 in lookup) # True
print(10 in lookup) # False
When to use: searching large lists, filtering data, checking duplicates.
Why it matters: sets make lookups instantly fast, improving performance dramatically.
Tip 5 — Use dict.get() to Avoid KeyError
Directly accessing a dictionary key can crash your code if the key does not exist.
Using .get() lets you provide a safe default value instead.
user = {"name": "Sachin"}
# Risky: may raise KeyError
# age = user["age"]
# Safe: returns None (or default) if key is missing
age = user.get("age", 0)
print(age) # 0
When to use: anytime you are not sure a key exists in a dictionary, especially when handling JSON or API responses.
Why it matters: prevents crashes, makes your code more robust, and keeps default behavior clear in one line.
Tip 6 — Use f-strings for Fast and Clean String Formatting
Python’s f-strings provide the cleanest and fastest way to insert variables into strings.
They are easier to read and much faster than % formatting or .format().
name = "Sachin"
score = 95
print(f"Hello {name}, your score is {score}.")
When to use: anytime you need dynamic text — logging, printing, messages, filenames, etc.
Why it matters: f-strings are faster, cleaner, more readable, and avoid syntax errors.
Updated daily — bookmark this page to learn new Python concepts every day.
Comments
Post a Comment