25 Amazing Python Tricks That Will Instantly Improve Your Code
Photo by Tudor Baciu on Unsplash

Python is a powerful and flexible language, but many developers only scratch the surface of what it can do. Whether you’re a beginner or an experienced programmer, these 25 Python tricks will help you write cleaner, faster, and more efficient code.
1. Swap Two Variables Without a Temporary Variable
Instead of using a temp variable, Python allows swapping in one line:
a, b = 5, 10
a, b = b, a
print(a, b) # Output: 10 5
2. Use List Comprehensions for Quick List Creation
List comprehensions are faster and more readable than traditional loops:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
3. Merge Two Dictionaries in One Line
In Python 3.9+, you can merge dictionaries easily:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = dict1 | dict2
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
4. Use Enumerate Instead of Range in Loops
Instead of using a manual index, use enumerate():
names = ['Aashish', 'Ash', 'Charlie']
for index, name in enumerate(names, start=1):
print(index, name)
5. Use zip() to Iterate Over Multiple Lists
zip() combines multiple iterables efficiently:
names = ['Aashish', 'Ash', 'Charlie']
scores = [90, 85, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")
6. Find the Most Frequent Element in a List
Use collections.Counter to find the most common item:
from collections import Counter
data = [1, 2, 2, 3, 3, 3, 4]
most_common = Counter(data).most_common(1)
print(most_common) # Output: [(3, 3)]
7. Flatten a Nested List in One Line
Use a list comprehension to flatten a list:
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]
8. Reverse a String in One Line
Use slicing to quickly reverse a string:
text = "Python"
print(text[::-1]) # Output: nohtyP
9. Check Memory Usage of an Object
Use sys.getsizeof() to check the memory size:
import sys
x = 42
print(sys.getsizeof(x)) # Output: 28 (size in bytes)
10. Use set() to Remove Duplicates from a List
Convert a list to a set to remove duplicates efficiently:
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers) # Output: [1, 2, 3, 4, 5]
11. Sort a List of Dictionaries by a Key
Use sorted() with a lambda function:
students = [{'name': 'Aashish', 'score': 88}, {'name': 'Ash', 'score': 95}]
sorted_students = sorted(students, key=lambda x: x['score'], reverse=True)
print(sorted_students)
12. Use defaultdict to Avoid KeyErrors
Automatically handle missing keys with defaultdict:
from collections import defaultdict
data = defaultdict(int)
data['missing_key'] += 1
print(data) # Output: defaultdict(<class 'int'>, {'missing_key': 1})
13. Use get() to Avoid KeyErrors in Dictionaries
Avoid KeyErrors with dict.get():
data = {'name': 'Alice'}
print(data.get('age', 25)) # Output: 25 (default value)
14. Check If Two Strings Are Anagrams
Use Counter to check if two words are anagrams:
from collections import Counter
def are_anagrams(s1, s2):
return Counter(s1) == Counter(s2)
print(are_anagrams("listen", "silent")) # Output: True
15. Use map() to Apply a Function to a List
Apply a function to each element of a list efficiently:
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
16. Use any() and all() for Logical Checks
Quickly check if any or all elements match a condition:
numbers = [0, 1, 2, 3]
print(any(numbers)) # Output: True
print(all(numbers)) # Output: False
17. Find the Index of the Maximum Value in a List
Use max() with enumerate():
numbers = [10, 20, 5, 30]
index_of_max = max(enumerate(numbers), key=lambda x: x[1])[0]
print(index_of_max) # Output: 3
18. Unpack Values Easily with * Operator
Python allows easy unpacking:
first, *middle, last = [1, 2, 3, 4, 5]
print(middle) # Output: [2, 3, 4]
19. Use join() for Fast String Concatenation
Avoid slow string concatenation inside loops:
words = ["Hello", "world"]
sentence = " ".join(words)
print(sentence) # Output: Hello world
20. Use timeit to Measure Execution Time
Benchmark your code using timeit:
import timeit
print(timeit.timeit('"-".join(str(n) for n in range(100))', number=10000))
21. Get the Most Common Elements from a List
Use Counter.most_common():
from collections import Counter
data = [1, 2, 2, 3, 3, 3, 4]
print(Counter(data).most_common(2)) # Output: [(3, 3), (2, 2)]
22. Create a Single-Line HTTP Server
Run a simple HTTP server using Python:
python -m http.server 8000
23. Use itertools for Infinite Iterators
itertools.cycle() repeats an iterable forever:
from itertools import cycle
colors = cycle(['red', 'green', 'blue'])
print(next(colors)) # Output: red
print(next(colors)) # Output: green
24. Use functools.lru_cache() for Caching
Speed up functions with caching:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
return n if n < 2 else fibonacci(n-1) + fibonacci(n-2)
25. Use dataclasses for Cleaner Object Creation
Avoid boilerplate code in classes:
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
p = Person("Aashish ", 25)
print(p) # Output: Person(name='Aashish', age=25)
These Python tricks will instantly improve your coding efficiency. Try them out, and let me know your favorite one! 🚀