4
Lesson 4
Transforming elements in list comprehension
List comprehension not only helps filter items but can also transform elements. This means you can change each item in the list or even create something entirely new based on the original data.
Let’s say you have a list of numbers[1, 2, 3, 4, 5] and want to create a new list where each number is doubled.
Without list comprehension:
Example 1: Doubling numbers
Let’s say you have a list of numbers
Without list comprehension:
numbers = [1, 2, 3, 4, 5] doubled = [] for num in numbers: doubled.append(num * 2) print(doubled) # Output: [2, 4, 6, 8, 10]
With list comprehension:
numbers = [1, 2, 3, 4, 5] doubled = [num * 2 for num in numbers] print(doubled) # Output: [2, 4, 6, 8, 10]
Example 2: Changing Strings
You can also modify strings. For example, let’s make all the words in a list uppercase.
Without list comprehension:
words = ["hello", "world", "python"] uppercase_words = [] for word in words: uppercase_words.append(word.upper()) print(uppercase_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
With list comprehension:
words = ["hello", "world", "python"] uppercase_words = [word.upper() for word in words] print(uppercase_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
Example 3: Complex transformations
You can use more complicated expressions in transformations. For example, let’s create a list of squared numbers from 1 to 9.
Without list comprehension:
squared_numbers = [] for num in range(1, 10): squared_numbers.append(num ** 2) print(squared_numbers) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81]
With list comprehension:
squared_numbers = [num ** 2 for num in range(1, 10)] print(squared_numbers) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Combining filtering and transformation
You can filter and transform in a single list comprehension. For example, let’s square only the even numbers from 1 to 10.
squared_evens = [num ** 2 for num in range(1, 11) if num % 2 == 0] print(squared_evens) # Output: [4, 16, 36, 64, 100]
What’s happening here?
1.
2.
3.
Why Use Transformation in List Comprehensions?
- Cleaner code: Everything is in one line, making it easier to read.
- Faster: List comprehensions are optimized for performance in Python.