Home »
Python
Python Code Snippets and Tricks for Better Code
Last Updated : February 13, 2026
Writing good Python code is not only about making it work. It should also be easy to read, clean, and efficient. Below are 11 useful Python code snippets and tricks that help you write better code with less effort.
- Swap Two Variables Without a Temporary Variable
- Check Multiple Conditions Using all() and any()
- Use List Comprehension for Cleaner Code
- Remove Duplicates Using set()
- Use enumerate() Instead of Index Variables
- Use zip() to Iterate Over Multiple Lists
- Default Dictionary to Avoid Key Errors
- Use Ternary Operator for Simple Conditions
- Reverse a String or List Easily
- Read a File Safely Using with
- Use try-except to Handle Errors Gracefully
1. Swap Two Variables Without a Temporary Variable
This technique allows the values of two variables to be exchanged without using an extra variable. Both values are reassigned at the same time, which keeps the logic simple and clear.
a = 10
b = 20
a, b = b, a
print(a, b)
When you run the above code, the output will be:
20 10
2. Check Multiple Conditions Using all() and any()
This approach is used to evaluate multiple conditions at the same time. It checks whether all values or at least one value satisfies a given condition without writing long conditional statements.
numbers = [2, 4, 6]
if all(n % 2 == 0 for n in numbers):
print("All numbers are even")
3. Use List Comprehension for Cleaner Code
This method is used to create a new list by applying an operation to each value in a sequence. It combines looping and assignment into a single expression, which reduces the number of lines of code.
squares = [x * x for x in range(1, 6)]
print(squares)
When you run the above code, the output will be:
[1, 4, 9, 16, 25]
4. Remove Duplicates Using set()
This technique is used to eliminate repeated values from a collection. It works by keeping only unique elements and discarding duplicates automatically.
data = [1, 2, 2, 3, 4, 4]
unique_data = list(set(data))
print(unique_data)
5. Use enumerate() Instead of Index Variables
This approach is used to access both the position and the value of each element during iteration. It removes the need to manually manage an index variable inside the loop.
languages = ["Python", "Java", "C++"]
for index, lang in enumerate(languages, start=1):
print(index, lang)
6. Use zip() to Iterate Over Multiple Lists
This technique is used to process multiple sequences together in a single loop. Elements at the same position from each sequence are accessed at the same time.
names = ["Amit", "Ravi", "Neha"]
scores = [85, 90, 88]
for name, score in zip(names, scores):
print(name, score)
7. Default Dictionary to Avoid Key Errors
This approach is used to handle missing keys safely in a key-value structure. When a key does not exist, a default value is automatically created instead of causing an error.
from collections import defaultdict
count = defaultdict(int)
count["apple"] += 1
print(count["apple"])
8. Use Ternary Operator for Simple Conditions
This technique is used to assign a value based on a condition in a single line. It replaces a longer conditional block with a concise expression
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)
9. Reverse a String or List Easily
This method is used to reverse the order of elements in a sequence. It works by accessing the elements from the end toward the beginning in a single operation.
text = "python"
print(text[::-1])
10. Read a File Safely Using with
This approach is used to safely work with files during read or write operations. The file is automatically closed after the task is completed, even if an error occurs.
with open("data.txt", "r") as file:
content = file.read()
print(content)
11. Use try-except to Handle Errors Gracefully
This technique handles errors that occur while a program is running. The error is managed in a controlled manner instead of stopping the program abruptly.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Advertisement
Advertisement