Python Tutorial - List Comprehensions
โก List Comprehensions - Fast Lists Banao
๐ Real Life Mein:
Shortcuts jo time bachaye:
๐ช "Saare products pe 10% off" - Ek line mein
๐ "1 to 100 numbers list" - Instantly
๐ฏ "Even numbers only" - Quick filter
๐ "Squares of numbers" - One liner
List Comprehension = For loop ka shortcut!
๐ Traditional Way vs โก List Comprehension
Old vs New
# Traditional way (5 lines)
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print(squares) # [1, 4, 9, 16, 25]
# List Comprehension (1 line!)
squares = [i ** 2 for i in range(1, 6)]
print(squares) # Same result!
๐ Syntax
[expression for item in iterable if condition]
Parts:
expression- Kya calculate karna haifor item in iterable- Loopif condition- Filter (optional)
๐ฐ Price Discount Example
# Original prices
prices = [100, 200, 150, 300, 50]
# 10% discount on all
discounted = [price * 0.9 for price in prices]
print(discounted) # [90, 180, 135, 270, 45]
# Only items > 100
expensive = [p for p in prices if p > 100]
print(expensive) # [200, 150, 300]
๐ฏ More Examples
Practical Use Cases
# Even numbers
evens = [n for n in range(1, 11) if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Convert to uppercase
names = ["rohan", "simran", "amit"]
upper_names = [name.upper() for name in names]
print(upper_names) # [ROHAN, SIMRAN, AMIT]
# Multiplication table
table_5 = [5 * i for i in range(1, 11)]
print(table_5) # [5, 10, 15...50]
When to Use: Simple operations ke liye use karo. Complex logic ho toh traditional loop better hai!
Example
nums = [x*2 for x in range(5)]
print(nums)