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.
enumerate()
π§© Section 7: Comprehensions with
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:
-
Create a list of squares of all odd numbers from 1 to 20.
-
Make a dictionary of character frequency from a string.
-
Flatten a 3x3 matrix using comprehension.
-
Create a set of vowels present in a string.
-
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!"