B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python List Comprehension Explained with Examples | LiveCodeProgramming
Python Installation First Python Program Control Flow if...else nested if else match-case logical-operators for loops while loops break / continue Functions Defining Functions Function Arguments Function return value Lambda Function Recursion Exception Handling Exception Handling Try Except Else and Finally Raise Exception Custom Exceptions File Handling File in python Read File Write File Append File Delete File Exception Handling

Python List Comprehension

List comprehension is a concise way to create lists using loops and conditions in one line.

List comprehension एक आसान तरीका है जिससे हम एक ही लाइन में loop और condition के साथ list बना सकते हैं।

1. Basic Example
squares = [x*x for x in range(5)]
print(squares)
Output:
[0, 1, 4, 9, 16]
2. With if Condition
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Output:
[0, 2, 4, 6, 8]
3. With if-else Condition
results = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(results)
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even']
4. Nested Loop Example
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs)
Output:
[(1, 3), (1, 4), (2, 3), (2, 4)]
5. Using Functions Inside
def square(x):
    return x * x

results = [square(x) for x in range(5)]
print(results)
Output:
[0, 1, 4, 9, 16]