Day 25 — Python Tricks (For Interviews)

This guide collects the most useful Python tricks that help in interviews, competitive coding, and writing clean, Pythonic code.

1. Multiple Variable Assignment & Swapping

a, b = 5, 10
a, b = b, a
print(a, b)  # 10 5
    

2. List Comprehensions

squares = [x**2 for x in range(6)]
print(squares)  # [0, 1, 4, 9, 16, 25]
    

3. Dictionary Comprehensions

nums = [1, 2, 3]
squares = {x: x**2 for x in nums}
print(squares)  # {1: 1, 2: 4, 3: 9}
    

4. Set Comprehensions

nums = [1, 2, 2, 3, 3]
unique = {x for x in nums}
print(unique)  # {1, 2, 3}
    

5. Using zip()

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
    print(name, score)
    

6. Using enumerate()

items = ["a", "b", "c"]
for index, value in enumerate(items, start=1):
    print(index, value)
    

7. String Reversal Trick

s = "Python"
print(s[::-1])  # nohtyP
    

8. Merge Dictionaries

dict1 = {"a": 1}
dict2 = {"b": 2}
merged = {**dict1, **dict2}
print(merged)  # {'a': 1, 'b': 2}
    

9. any() and all()

nums = [2, 4, 6]
print(all(x % 2 == 0 for x in nums))  # True
print(any(x > 5 for x in nums))       # True
    

10. Ternary Operator

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)  # Adult
    

11. Context Manager (with)

with open("file.txt", "w") as f:
    f.write("Hello World")
    

12. F-Strings

name = "Alice"
score = 95
print(f"{name} scored {score} marks")
    

13. Unpacking with *

nums = [1, 2, 3, 4]
print(*nums)  # 1 2 3 4
    

14. Using **kwargs and *args

def demo(*args, **kwargs):
    print(args)
    print(kwargs)

demo(1, 2, 3, a=10, b=20)
    

15. Inline if with print()

x = 5
print("Even") if x % 2 == 0 else print("Odd")
    

16. Using collections.Counter

from collections import Counter
print(Counter("mississippi"))  # counts characters
    

17. Using defaultdict

from collections import defaultdict
d = defaultdict(int)
d["a"] += 1
print(d)  # {'a': 1}
    

18. Using itertools

import itertools
nums = [1, 2, 3]
print(list(itertools.permutations(nums)))
    

19. Lambda + map + filter + reduce

from functools import reduce
nums = [1, 2, 3, 4]
print(list(map(lambda x: x*2, nums)))
print(list(filter(lambda x: x%2==0, nums)))
print(reduce(lambda x,y: x+y, nums))
    

20. Sorted with key

data = ["apple", "banana", "pear"]
print(sorted(data, key=len))  # ['pear', 'apple', 'banana']
    

21. Using __slots__ to save memory

class Person:
    __slots__ = ["name", "age"]
    def __init__(self, name, age):
        self.name, self.age = name, age
    

22. Chained Comparison

x = 10
print(5 < x < 15)  # True
    

23. Using is vs ==

a = [1,2]
b = [1,2]
print(a == b)  # True (values equal)
print(a is b)  # False (different objects)
    

24. Try-Else in Exception Handling

try:
    num = int("10")
except ValueError:
    print("Error")
else:
    print("Success")  # Runs if no exception
    

25. Walrus Operator (Python 3.8+)

if (n := len([1,2,3,4])) > 3:
    print(f"List is long ({n} elements)")