# List Comprehension
new_list = [expression for item in iterable if condition]
List comprehension is a concise and efficient way to create lists in Python. It allows you to generate a new list by performing operations on each item of an existing iterable (e.g., list, tuple, string) in a single line of code. List comprehensions are more readable and often faster than traditional loop-based list creation. Let's explore some examples of list comprehension in Python.
Example 1: Squares of numbers from 1 to 5:
```python
# Using a traditional loop
squares = []
for i in range(1, 6):
squares.append(i**2)
print(squares) # Output: [1, 4, 9, 16, 25]
# Using list comprehension
squares = [i**2 for i in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
```
Example 2: Filtering even numbers from a list:
```python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using a traditional loop
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers) # Output: [2, 4, 6, 8, 10]
# Using list comprehension with a condition
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]
```
Example 3: Converting strings to uppercase:
```python
words = ["hello", "world", "python", "list", "comprehension"]
# Using a traditional loop
upper_words = []
for word in words:
upper_words.append(word.upper())
print(upper_words) # Output: ['HELLO', 'WORLD', 'PYTHON', 'LIST', 'COMPREHENSION']
# Using list comprehension with a method call
upper_words = [word.upper() for word in words]
print(upper_words) # Output: ['HELLO', 'WORLD', 'PYTHON', 'LIST', 'COMPREHENSION']
```
Example 4: Nested list comprehension - Matrix transpose:
```python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Using nested loops
transpose = []
for i in range(len(matrix[0])):
row = [matrix[j][i] for j in range(len(matrix))]
transpose.append(row)
print(transpose) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# Using nested list comprehension
transpose = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
print(transpose) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
```
List comprehensions provide a concise and readable way to create new lists based on existing data and conditions. They are widely used in Python programming due to their simplicity and efficiency. However, it's essential to use them judiciously to maintain code readability and avoid excessive complexity.
Comments
Post a Comment