List comprehension is a concise way to create new lists by applying an expression to each item in an existing iterable like a list, tuple or range. It helps to write clean, readable and efficient code compared to traditional loops.
Suppose you want to square every number in a list:
a = [2, 3, 4, 5]
res = [val ** 2 for val in a]
print(res)
Output
[4, 9, 16, 25]
Explanation: res = [val ** 2 for val in a] use **list comprehension **to create a new list by squaring each number in a.
Syntax
[expression for item in iterable if condition]
Parameters:
- expression: operation or value to include in the new list.
- item: current element from the iterable.
- iterable: sequence like a list, tuple or range.
- if condition (optional): filter to include only items that satisfy the condition.
Conditional Statements in List Comprehension
List comprehensions can use conditions to select or transform items based on specific rules. This allows creating customised lists more concisely and improves code readability and efficiency.
Example 1: This code uses a list comprehension with a condition to create a new list with only even numbers from list a.
a = [1, 2, 3, 4, 5]
res = [val for val in a if val % 2 == 0]
print(res)
Output
[2, 4]
Example 2: Here, list comprehension is used with a condition to create a new list with numbers greater than 10 from list b.
b = [5, 12, 7, 18, 3, 20]
res = [val for val in b if val > 10]
print(res)
Output
[12, 18, 20]
For Loop vs List Comprehension
For Loop
- Uses multiple lines of code
- Requires manual appending of elements
- Better for complex logic and conditions
- More readable for long operations
List Comprehension
- Uses a single line of code.
- Creates the list directly.
- Better for simple and concise operations
- More compact and faster to write
Top comments (0)