Applying the map()
function to a list in Python allows us to apply a given function to each element of the list. Here are two examples:
Example 1:
numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x ** 2, numbers)) print(f"Squared numbers: {squared_numbers}")
Output:
Squared numbers: [1, 4, 9, 16, 25]
Example 2:
names = ['Alice', 'Bob', 'Charlie'] uppercase_names = list(map(str.upper, names)) print(f"Uppercase names: {uppercase_names}")
Output:
Uppercase names: [‘ALICE’, ‘BOB’, ‘CHARLIE’]