# Define a function to square a number def square(x): return x * x # Define a list of numbers numbers = [1, 2, 3, 4, 5] # Apply the square function to each item in the list using map squared_numbers = map(square, numbers) # Convert the result to a list and print it squared_numbers_list = list(squared_numbers) print(squared_numbers_list)
[1, 4, 9, 16, 25]
# Define a list of numbers numbers = [1, 2, 3, 4, 5] # Use map with a lambda function to square each number squared_numbers = map(lambda x: x * x, numbers) # Convert the result to a list and print it squared_numbers_list = list(squared_numbers) print(squared_numbers_list)
[1, 4, 9, 16, 25]
# Define a list of strings representing numbers str_numbers = ['1', '2', '3', '4', '5'] # Use map to convert each string to an integer int_numbers = map(int, str_numbers) # Convert the result to a list and print it int_numbers_list = list(int_numbers) print(int_numbers_list)
[1, 2, 3, 4, 5]
# Define two lists of numbers list1 = [1, 2, 3] list2 = [4, 5, 6] # Define a function to add two numbers def add(x, y): return x + y # Use map to add elements from both lists added_numbers = map(add, list1, list2) # Convert the result to a list and print it added_numbers_list = list(added_numbers) print(added_numbers_list)
[5, 7, 9]
# Define a list of dictionaries students = [ {'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 90}, {'name': 'Charlie', 'score': 78} ] # Define a function to extract student names def get_name(student): return student['name'] # Use map to extract names from the list of dictionaries names = map(get_name, students) # Convert the result to a list and print it names_list = list(names) print(names_list)
['Alice', 'Bob', 'Charlie']
from functools import reduce # Define a list of numbers numbers = [1, 2, 3, 4, 5] # Use map to square each number squared_numbers = map(lambda x: x * x, numbers) # Use filter to select only even squared numbers even_squared_numbers = filter(lambda x: x % 2 == 0, squared_numbers) # Use reduce to sum the even squared numbers sum_even_squared_numbers = reduce(lambda x, y: x + y, even_squared_numbers) print(sum_even_squared_numbers)
20