Python List Comprehension
List comprehension provides a concise way to create lists using a single line of code. It is often more readable and faster than traditional loops.
List comprehension से आप एक लाइन में आसानी से lists बना सकते हैं। यह traditional loops से ज्यादा readable और तेज होता है।
Example 1: Square Numbers
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
Create a list of squares of numbers.
संख्या के वर्ग का list बनाएं।
Output:
Example 2: Even Numbers Filter
numbers = range(10)
evens = [x for x in numbers if x % 2 == 0]
print(evens)
Create a list of even numbers from 0 to 9.
0 से 9 तक के सम संख्याओं की list बनाएं।
Output:
Example 3: Convert to Uppercase
fruits = ['apple', 'banana', 'cherry']
upper_fruits = [f.upper() for f in fruits]
print(upper_fruits)
Convert all fruit names to uppercase.
सभी फल के नाम uppercase में बदलें।
Output:
Example 4: Nested List Comprehension (Matrix Transpose)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(3)]
print(transpose)
Transpose a matrix using nested list comprehension.
Nested list comprehension से matrix का transpose बनाएं।
Output:
Example 5: Conditional Expression in Comprehension
numbers = range(10)
labels = ['Even' if x % 2 == 0 else 'Odd' for x in numbers]
print(labels)
Label numbers as 'Even' or 'Odd' using conditional expressions.
संख्या को 'Even' या 'Odd' के रूप में लेबल करें।
Output: