10 Python Tricks Every Beginner Should Know (With Code Examples)
Python is a beautiful and beginner-friendly language—but it has many hidden gems that can make your code cleaner, faster, and more Pythonic. In this post, we’ll look at 10 simple but powerful Python tricks, each explained in a beginner-friendly way with real code examples.
Written By: Nivesh Bansal Linkedin, GitHub, Instagram
1. Swapping Variables Without a Temporary Variable
Instead of this:
a = 10
b = 20
temp = a
a = b
b = temp
You can do:
a, b = b, a
print(a, b) # Output: 20 10
Python lets you swap variables in a single line using tuple unpacking.
2. Using List Comprehensions
Instead of:
squares = []
for i in range(10):
squares.append(i * i)
Try this:
squares = [i * i for i in range(10)]
print(squares)
Cleaner and faster!
3. Merging Dictionaries (Python 3.9+)
You might normally merge two dictionaries like this:
dict1 = {'a': 1}
dict2 = {'b': 2}
dict1.update(dict2)
Now you can just write:
dict1 = {'a': 1}
dict2 = {'b': 2}
merged = dict1 | dict2
print(merged) # Output: {'a': 1, 'b': 2}
4. Using enumerate() Instead of Range + Index
Bad way:
fruits = ['apple', 'banana', 'mango']
for i in range(len(fruits)):
print(i, fruits[i])
Better:
fruits = ['apple', 'banana', 'mango']
for i, fruit in enumerate(fruits):
print(i, fruit)
More readable and Pythonic!
5. Using zip() to Iterate Over Multiple Lists
Instead of:
names = ['Alice', 'Bob']
ages = [25, 30]
for i in range(len(names)):
print(names[i], ages[i])
Use:
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
print(name, age)
6. Unpacking with Asterisk (*)
You can unpack values like this:
a, *b, c = [1, 2, 3, 4, 5]
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5
Useful for flexible argument handling or ignoring middle values.
7. Using _ as a Throwaway Variable
If you don’t care about a value in a loop:
for _ in range(5):
print("Hello")
Underscore _ means “I don’t care about this value.”
8. Set for Unique Elements
Instead of removing duplicates manually:
nums = [1, 2, 2, 3, 3, 3]
unique = list(set(nums))
print(unique) # Output: [1, 2, 3]
Sets remove duplicates automatically!
9. Get Dictionary Values with get()
Avoid this:
data = {'name': 'Alice'}
print(data['age']) # KeyError!
Use this:
print(data.get('age', 'Not Found')) # Output: Not Found
Safer way to access keys.
10. Using any() and all()
Check conditions across a list:
nums = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in nums)) # True (all even)
print(any(n > 5 for n in nums)) # True (some > 5)
Final Thoughts
These small Python tricks can improve your code readability, efficiency, and style. Keep experimenting and building projects—that’s the best way to master Python!
Which one of these tricks was new to you? Let me know in the comments. 🚀
Top comments (2)
Awesome roundup—so many handy tips!
thanku Buddy!