πŸ”·Python Basics

image

🐍 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()

Leave a Comment

Your email address will not be published. Required fields are marked *