Python Top Tricks & Hacks Every Coder Should Know
π Python Top Tricks & Hacks Every Coder Should Know π
Python is one of the most beloved programming languages in the world β not just because itβs easy to learn, but also because it hides powerful tricks and hacks under its hood. These little gems can make your code shorter, smarter, and more Pythonic. π‘
In this blog, weβll uncover top Python tricks & hacks that will help you level up your coding game. Each trick comes with examples to make sure you can start using them right away. And donβt miss the Pro Bonus Tips at the end! π₯
1οΈβ£ Multiple Variable Assignment in One Line βοΈ
Instead of writing several lines, Python allows assigning multiple variables in one shot.
# Normal way
a = 10
b = 20
c = 30
# Pythonic way
a, b, c = 10, 20, 30
print(a, b, c) # Output: 10 20 30
β Cleaner, shorter, and great for readability.
2οΈβ£ Swapping Variables Without Temporary Variable π
Forget the old-school temp
variable trick!
x, y = 5, 10
x, y = y, x
print(x, y) # Output: 10 5
π This is one of the simplest yet most loved Python tricks.
3οΈβ£ Using enumerate()
Instead of Range + Index π
When looping through lists, enumerate()
saves effort.
fruits = ["apple", "banana", "cherry"]
# Without enumerate
for i in range(len(fruits)):
print(i, fruits[i])
# With enumerate
for index, fruit in enumerate(fruits):
print(index, fruit)
π― Much cleaner and more Pythonic.
4οΈβ£ List Comprehensions: Write Short & Clean Loops β¨
Instead of writing multiple lines for loops, use list comprehensions.
# Normal loop
squares = []
for i in range(1, 6):
squares.append(i * i)
# List comprehension
squares = [i * i for i in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
π₯ Bonus: You can even add conditions inside comprehensions.
even_squares = [i*i for i in range(1, 11) if i % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
5οΈβ£ Dictionary Comprehensions ποΈ
Same as lists, but for dictionaries.
# Normal way
squares = {}
for i in range(1, 6):
squares[i] = i * i
# Dictionary comprehension
squares = {i: i * i for i in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
6οΈβ£ Using zip()
to Combine Lists π€
Want to pair two lists together? Use zip()
.
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
Output:
Alice scored 85
Bob scored 90
Charlie scored 95
π Super useful in data processing tasks.
7οΈβ£ Unpacking with *
and **
β
Python allows you to unpack lists/tuples easily.
numbers = [1, 2, 3, 4, 5]
print(*numbers)
# Output: 1 2 3 4 5
You can also unpack dictionaries in functions:
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
person = {"name": "John", "age": 25}
greet(**person)
# Output: Hello John, you are 25 years old.
8οΈβ£ Using any()
and all()
for Quick Checks β
Instead of writing loops, use these built-ins.
nums = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in nums)) # True
print(any(n > 7 for n in nums)) # True
π‘ all()
= All conditions true
π‘ any()
= At least one condition true
9οΈβ£ The Power of collections.Counter
π’
Count items in a list in seconds.
from collections import Counter
fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]
count = Counter(fruits)
print(count)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
π― Great for frequency analysis tasks.
π Using f-strings
for Cleaner Formatting π
No need to mess with +
or .format()
.
name = "Lakhveer"
age = 25
print(f"My name is {name} and I am {age} years old.")
β¨ Short, powerful, and readable.
π Bonus Pro Tips for Python Coders π
β
Use virtual environments (venv
, pipenv
, or poetry
) to manage dependencies.
β
Apply type hints (def func(x: int) -> str
) for cleaner and safer code.
β
Learn decorators for reusable code functionality.
β
Use with
context managers for safe file handling.
β
Master generators for memory-efficient coding.
β¨ Final Thoughts
Python is already powerful, but these tricks and hacks make it feel magical β¨. By writing clean, Pythonic code, you save time, reduce bugs, and impress others with your elegance.
π Try using at least 2β3 of these hacks in your next project and see the difference!
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.