Master Python Comprehensions 🧠 | One-Liner Magic for Clean Code #12 || Python ka Pitara || DeathCode - DeathCode

List, Dict Comprehensions & Pythonic Short-hand Syntax


πŸš€ Introduction

"Kya aapne kabhi aisa likha hai?"

 
new_list = []
 
for i in range(10):
 
Β  Β  if i % 2 == 0:
 
Β  Β  Β  Β  new_list.append(i * i)
 

"Ab same kaam 1 line me bhi ho sakta hai:"

 
new_list = [i * i for i in range(10) if i % 2 == 0]
 

"Yeh hai Python ka Comprehension Power πŸ’₯ β€” Let’s master it today!"


🧱 Section 1: List Comprehension Basics

🎯 Syntax:

 
[expression for item in iterable if condition]
 

βœ… Example:

 
squares = [x ** 2 for x in range(10)]
 

βœ… With Condition:

 
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
 

🧠 Readable β†’ Reusable β†’ Pythonic

βœ… It’s faster than traditional for loops (benchmarked)


⚑ Section 2: Advanced List Comprehension

πŸ“Œ Nested Loops:

 
pairs = [(x, y) for x in range(3) for y in range(3)]
 

πŸ“Œ Using if...else inside:

 
result = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
 

πŸ“Œ Flatten a 2D list:

 
matrix = [[1,2], [3,4], [5,6]]
 
flat = [num for row in matrix for num in row]
 

β›” Don’t over-nest! Keep readability in mind.


🧠 Section 3: Dict Comprehension

🎯 Syntax:

 
{key: value for item in iterable}
 

βœ… Example:

 
squares = {x: x ** 2 for x in range(5)}
 

βœ… With condition:

 
even_square_map = {x: x ** 2 for x in range(10) if x % 2 == 0}
 

🧠 Create frequency map:

 
text = "banana"
 
freq = {ch: text.count(ch) for ch in text}
 

πŸ”„ Section 4: Set Comprehension

🎯 Syntax:

 
{expression for item in iterable}
 

βœ… Example:

 
unique_chars = {ch for ch in "hello world"}
 

🧠 Use when duplicates aren’t needed.


βœ‚οΈ Section 5: Short-hand One-Liners

πŸ“Œ Ternary Expressions:

 
status = "Adult" if age >= 18 else "Child"
 

πŸ“Œ Shorthand Loops:

 
[print(i) for i in range(5)] Β # Not preferred for side effects, but useful sometimes
 

πŸ“Œ Shorthand with lambda:

 
is_even = lambda x: x % 2 == 0
 

πŸ“Œ Real-world (File I/O):

 
lines = [line.strip() for line in open("file.txt")]
 

⚠️ Section 6: Pitfalls & Best Practices

βœ… DO:

  • Keep it readable

  • Use for transforming data

  • Use with filters

🚫 DON’T:

  • Avoid multiple nested for-loops unless necessary

  • Avoid side effects (like print() or file write) in comprehensions

πŸ’‘ Tip:

Use normal loops for complex logic and comprehensions for clean transformations.


🧩 Section 7: Comprehensions with enumerate()

 
data = ["a", "b", "c"]
 
mapped = {i: val for i, val in enumerate(data)}
 

πŸš€ Clean index-value mapping in a single line


🧠 Section 8: Performance Secrets

  • List comprehensions are 30-40% faster than loops

  • Why? β†’ They're implemented in C, and avoid multiple append() calls

  • Cleaner memory usage for small-to-mid size data


🏁 See ya!

"Ab aap master ban chuke ho comprehensions ke β€” ab likhiye Pythonic code, clean code!"

Practice Time:

  1. Create a list of squares of all odd numbers from 1 to 20.

  2. Make a dictionary of character frequency from a string.

  3. Flatten a 3x3 matrix using comprehension.

  4. Create a set of vowels present in a string.

  5. Build a name: length map using dict comprehension.


πŸ”œ Teaser for Next Part:

"Agle video me hum dekhenge kuch Python ke built-in functions β€” jinke peeche chhupi hai bhayankar power: Β  map, filter, zip, enumerate, any, all β€” aur jaanenge unka behind-the-scenes magic, secrets aur real-world usage!"

Β© 2024 DeathCode. All Rights Reserved.