Python Tutorial - List Comprehensions

Unlock Premium Features: AI explanations (Hinglish), Indian voice & Videos
Sign Up Free

โšก 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 hai
  • for item in iterable - Loop
  • if 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!

๐Ÿค– AI Tutor Unlock Karo!

Apni language mein coding seekho - Hindi, Marathi, Gujarati aur 10+ Indian languages mein!

  • Hinglish mein explanations
  • Real-life examples
  • Beginner-friendly
Free Signup Karo

Example

nums = [x*2 for x in range(5)]
print(nums)