map() function
Map() is a built-in python function. It gets a list and a function that gets only one parameter.
Map returns a new list in which each item is the result of applying the function with the appropriate
value in the original list.
Watch the example:
#map
def triple(x):
return(x * 3)
original_list = [1, 2, 3, 4, 5]
print(original_list)
new_map = map(triple, original_list)
#print a map object
print(new_map)
#print a list object
new_list = list(new_map)
print(new_list)
Exercise
- Create a function that calculate the square of a number.
- Create a list of arbitrary numbers.
- Use the map() function to apply the function on the list items.
- Print out the list.
#Create a function
#Use the map() function
#Print out