List comprehension is a concise way to create lists using loops and conditions in one line.
List comprehension एक आसान तरीका है जिससे हम एक ही लाइन में loop और condition के साथ list बना सकते हैं।
squares = [x*x for x in range(5)]
print(squares)
Output:
[0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Output:
[0, 2, 4, 6, 8]
results = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(results)
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even']
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs)
Output:
[(1, 3), (1, 4), (2, 3), (2, 4)]
def square(x):
return x * x
results = [square(x) for x in range(5)]
print(results)
Output:
[0, 1, 4, 9, 16]