
π PYTHON TIPS & TRICKS β WITH SIMPLE VISUAL DIAGRAMS
β 1. Using List Comprehensions (Fast & Clean)
π₯ Tip
Instead of writing long loops, use list comprehensions.
Example:
squares = [x*x for x in range(10)]
Visual Diagram:
[Loop] β [Operation] β [New List]
range(10) ββ> x*x ββ> [0, 1, 4, 9, 16 ...]
β 2. Use enumerate() Instead of range(len())
Without enumerate:
for i in range(len(items)):
print(i, items[i])
With enumerate:
for i, value in enumerate(items):
print(i, value)
Diagram:
List β enumerate β (index, value) pairs
β 3. Multiple Variable Assignment (Unpacking)
a, b, c = 1, 2, 3
Diagram:
[1, 2, 3] β (a, b, c)
Supports:
a, *b = [10, 20, 30, 40]
β 4. Using zip() to Combine Lists
names = ["Ram", "Shyam"]
scores = [90, 85]
for n, s in zip(names, scores):
print(n, s)
Diagram:
names: [Ram Shyam]
scores: [90 85]
zip β (Ram,90), (Shyam,85)
β 5. Using f-strings for Clean Formatting
name = "TK"
score = 95
print(f"{name} scored {score} marks")
Diagram:
"{} {} {}".format(...) β β old
f"{var} text" β β new
β 6. Dictionary Comprehensions
square_map = {x: x*x for x in range(5)}
Diagram:
for each x β store as {key: value}
0β0, 1β1, 2β4, 3β9, 4β16
β 7. Using βinβ Keyword for Fast Membership Check
if 'tk' in username:
print("valid")
Diagram:
String / List / Set
β
"in" checks membership
β **8. Using *args and kwargs
*args β variable number of arguments
def add(*nums):
return sum(nums)
**kwargs β key-value arguments
def info(**data):
print(data)
Diagram:
add(1,2,3) β *args β [1,2,3]
info(name='TK') β **kwargs β {'name':'TK'}
β 9. Lambda Functions (Inline Mini Functions)
square = lambda x: x*x
print(square(5))
Diagram:
lambda x: x*x
β
Tiny anonymous function
β 10. Using map(), filter(), reduce()
map β transform elements
list(map(lambda x: x*2, [1,2,3]))
filter β keep matching elements
list(filter(lambda x: x>2, [1,2,3]))
reduce β accumulate
from functools import reduce
reduce(lambda a,b: a+b, [1,2,3])
Diagram:
[1,2,3] β map β [2,4,6]
[1,2,3] β filter(x>2) β [3]
[1,2,3] β reduce(add) β 6
β 11. Using Try/Except in One Line
value = int(input) if input.isdigit() else 0
β 12. Use of Set for FAST lookups
unique = set(my_list)
Diagram:
List β (remove duplicates) β Set (Fast O(1))
β BONUS β ADVANCED PYTHON TRICKS
β 13. Swap variables without temp
a, b = b, a
β 14. Merging Dictionaries
d1 = {"a":1}
d2 = {"b":2}
merged = {**d1, **d2}
β 15. Inline If (Ternary)
status = "Pass" if score >= 40 else "Fail"
β 16. List slicing tricks
rev = my_list[::-1] # reverse
first3 = my_list[:3] # first 3
last3 = my_list[-3:] # last 3
β 17. Convert list to string
",".join(["A","B","C"])
β 18. Most useful builtin functions
sorted()any()all()sum()max()min()round()
