This guide collects the most useful Python tricks that help in interviews, competitive coding, and writing clean, Pythonic code.
a, b = 5, 10 a, b = b, a print(a, b) # 10 5
squares = [x**2 for x in range(6)] print(squares) # [0, 1, 4, 9, 16, 25]
nums = [1, 2, 3] squares = {x: x**2 for x in nums} print(squares) # {1: 1, 2: 4, 3: 9}
nums = [1, 2, 2, 3, 3] unique = {x for x in nums} print(unique) # {1, 2, 3}
names = ["Alice", "Bob", "Charlie"] scores = [85, 92, 78] for name, score in zip(names, scores): print(name, score)
items = ["a", "b", "c"] for index, value in enumerate(items, start=1): print(index, value)
s = "Python" print(s[::-1]) # nohtyP
dict1 = {"a": 1} dict2 = {"b": 2} merged = {**dict1, **dict2} print(merged) # {'a': 1, 'b': 2}
nums = [2, 4, 6] print(all(x % 2 == 0 for x in nums)) # True print(any(x > 5 for x in nums)) # True
age = 20 status = "Adult" if age >= 18 else "Minor" print(status) # Adult
with open("file.txt", "w") as f: f.write("Hello World")
name = "Alice" score = 95 print(f"{name} scored {score} marks")
nums = [1, 2, 3, 4] print(*nums) # 1 2 3 4
def demo(*args, **kwargs): print(args) print(kwargs) demo(1, 2, 3, a=10, b=20)
x = 5 print("Even") if x % 2 == 0 else print("Odd")
from collections import Counter print(Counter("mississippi")) # counts characters
from collections import defaultdict d = defaultdict(int) d["a"] += 1 print(d) # {'a': 1}
import itertools nums = [1, 2, 3] print(list(itertools.permutations(nums)))
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))
data = ["apple", "banana", "pear"] print(sorted(data, key=len)) # ['pear', 'apple', 'banana']
class Person: __slots__ = ["name", "age"] def __init__(self, name, age): self.name, self.age = name, age
x = 10 print(5 < x < 15) # True
a = [1,2] b = [1,2] print(a == b) # True (values equal) print(a is b) # False (different objects)
try: num = int("10") except ValueError: print("Error") else: print("Success") # Runs if no exception
if (n := len([1,2,3,4])) > 3: print(f"List is long ({n} elements)")