Python_Hacks
1. Swapping Two Variables (No Temp Variable)
a, b = 5, 10
a, b = b, a
2. One-Line List Flattening
nested = [[1, 2], [3, 4], [5]]
flat = [item for sublist in nested for item in sublist]
3. Chaining Comparisons
x = 10
if 5 < x < 15:
print("x is between 5 and 15")
4. Multiple Variable Assignment in One Line
name, age, city = "John", 25, "NYC"
5. Ternary Conditional Operator
x = 5
status = "Even" if x % 2 == 0 else "Odd"
6. List Comprehensions (with Condition)
squares = [x*x for x in range(10) if x % 2 == 0]
7. Use any() and all() Smartly
nums = [2, 4, 6]
print(all(n % 2 == 0 for n in nums)) # True
print(any(n > 5 for n in nums)) # True
8. String Reversal
s = "hello"
print(s[::-1]) # 'olleh'
9. Swap Elements in a List
arr = [1, 2, 3, 4]
arr[0], arr[-1] = arr[-1], arr[0]
10. Merging Two Dictionaries (Python 3.9+)
dict1 = {'a': 1}
dict2 = {'b': 2}
merged = dict1 | dict2
11. Use enumerate() Instead of Range
names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names, start=1):
print(f"{index}: {name}")
12. Dictionary Comprehension
squares = {x: x*x for x in range(5)}
13. Use zip() to Pair Items
names = ["a", "b", "c"]
scores = [85, 90, 95]
paired = dict(zip(names, scores))
14. Get Frequency Count Using collections.Counter
from collections import Counter
nums = [1, 2, 2, 3, 3, 3]
freq = Counter(nums)
15. One-Liner Fibonacci (Generator)
fib = lambda n: n if n <= 1 else fib(n-1) + fib(n-2)
16. Use pathlib for File Paths (Modern Way)
from pathlib import Path
path = Path("myfolder") / "file.txt"
17. Unpack Lists or Tuples Smartly
a, *middle, b = [1, 2, 3, 4, 5]
18. __slots__ to Save Memory in Classes
class MyClass:
__slots__ = ['x', 'y']
19. Python's Walrus Operator (Python 3.8+)
if (n := len("Hello")) > 3:
print(f"Length is {n}")
20. Use get() with Default in Dict
data = {"name": "Alice"}
print(data.get("age", 25)) # Returns 25 if 'age' not found
squares = {x: x*x for x in range(5)}
names = ["a", "b", "c"]
scores = [85, 90, 95]
paired = dict(zip(names, scores))
14. Get Frequency Count Using collections.Counter
from collections import Counter
nums = [1, 2, 2, 3, 3, 3]
freq = Counter(nums)
15. One-Liner Fibonacci (Generator)
fib = lambda n: n if n <= 1 else fib(n-1) + fib(n-2)
16. Use pathlib for File Paths (Modern Way)
from pathlib import Path
path = Path("myfolder") / "file.txt"
17. Unpack Lists or Tuples Smartly
a, *middle, b = [1, 2, 3, 4, 5]
18. __slots__ to Save Memory in Classes
class MyClass:
__slots__ = ['x', 'y']
19. Python's Walrus Operator (Python 3.8+)
if (n := len("Hello")) > 3:
print(f"Length is {n}")
20. Use get() with Default in Dict
data = {"name": "Alice"}
print(data.get("age", 25)) # Returns 25 if 'age' not found
from collections import Counter
nums = [1, 2, 2, 3, 3, 3]
freq = Counter(nums)
fib = lambda n: n if n <= 1 else fib(n-1) + fib(n-2)
from pathlib import Path
path = Path("myfolder") / "file.txt"
a, *middle, b = [1, 2, 3, 4, 5]
class MyClass:
__slots__ = ['x', 'y']
if (n := len("Hello")) > 3:
print(f"Length is {n}")
data = {"name": "Alice"}
print(data.get("age", 25)) # Returns 25 if 'age' not found