![]() |
VOOZH | about |
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:
[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.
[expression for item in iterable if condition]
Parameters:
List comprehensions can use conditions to select or transform items based on specific rules. This allows creating customized 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.
[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.
[12, 18, 20]
1. Creating a list from a range: One can quickly create a list of numbers within a specific range using list comprehension.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Using nested loops: A list of all coordinate pairs in a 3x3 grid can be generated by combining two loops inside a list comprehension.
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
3. Flattening a list of lists: A nested list (matrix) can be transformed into a single flat list by iterating through each sublist and its elements.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
| For Loop | List Comprehension |
|---|---|
| Uses multiple lines of code | Uses a single line of code |
| Requires manual appending of elements | Creates the list directly |
| Better for complex logic and conditions | Better for simple and concise operations |
| More readable for long operations | More compact and faster to write |