🏠 Home 📚 Chapters
HomeChapters › Chapter 16
CHAPTER 16

List Comprehension

एक line में powerful lists, dicts बनाना

Advertisement

List Comprehension

List comprehension से loop की जगह एक line में list बना सकते हैं।
python
# Normal way vs Comprehension

# Old way (4 lines)
squares = []
for i in range(1, 6):
    squares.append(i**2)

# Comprehension (1 line) ✨
squares = [i**2 for i in range(1, 6)]
print(squares)   # [1, 4, 9, 16, 25]

# Condition के साथ
evens = [x for x in range(1, 21) if x%2==0]
print(evens)

# String transform
fruits = ["apple", "banana", "mango"]
upper = [f.upper() for f in fruits]
print(upper)
OUTPUT
[1, 4, 9, 16, 25] [2, 4, 6, 8, 10, ...]
Advertisement

Dict और Set Comprehension

Dictionary और Set भी comprehension से बना सकते हैं।
python
# Dict comprehension
fruits = ["apple", "banana", "mango"]
word_len = {w: len(w) for w in fruits}
print(word_len)
# {'apple': 5, 'banana': 6, 'mango': 5}

# Set comprehension
nums = [-2, -1, 0, 1, 2]
squares = {x**2 for x in nums}
print(squares)   # {0, 1, 4} unique

# Nested comprehension
matrix = [[i*j for j in range(1,4)] 
          for i in range(1,4)]
print(matrix)
OUTPUT
{'apple': 5, 'banana': 6, 'mango': 5} {0, 1, 4}

🎯 QUICK QUIZ — Chapter 16

List Comprehension क्या है?
Advertisement
🏠 अगला →