Applying a function to each element of a list is a common task in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to use list comprehension and the map()
function to apply a function to each element of a list efficiently.
Example 1:
numbers = [1, 2, 3, 4, 5] squared_numbers = [x ** 2 for x in numbers] print(squared_numbers)
Output: [1, 4, 9, 16, 25]
Example 2:
names = ['Alice', 'Bob', 'Charlie'] uppercase_names = list(map(str.upper, names)) print(uppercase_names)
Output: [‘ALICE’, ‘BOB’, ‘CHARLIE’]