Python Map Exercises
Let’s check out some exercises that will help understand map() better.
Write a map function that adds plus 5 to each item in the list.
Write a map function that returns the squares of the items in the list.
Write a map function that adds "Hello, " in front of each item in the list.
Using map() function and len() function create a list that's consisted of lengths of each element in the first list.
Using map() function and lambda add each elements of two lists together. Use a lambda with two arguments.
Using map() function and lambda and count() function create a list which consists of the number of occurence of letter: a.
Using map() function and lambda and count() function create a list consisted of the number of occurence of both letters: A and a.
Very similar to previous but you just need to add one thing. Maybe if everything was in lower case it would be easier to count?
lower is a string method that converts all characters in a string to lower case.
Simply use as:
lst2 = list(map(lambda x: x.lower().count("a"), lst1))
Using map() function, first return a new list with absolute values of existing list. Then for ans_1, find the total sum of the new list's elements.
map() function takes two arguments, first the function, then comma and second the name of the list to be used for the mapping function.
abs function can be used to calculate absolute values of integers and floats. It can also be iterated through lists using map function.
A quick way to calculate sum of iterables (such as lists, tuples and dictionaries in Python) is the sum function.
Simply use it as:
Finally, don’t forget, map function similar to filter function returns a map object that’s not very readable for humans although it works great for computers. To convert this weird object to something presentable we use list function which creates a proper Python list from another iterable object (in this case a map object).
Simply use it as:
new_lst = list(map(abs, lst))
ans_1 = sum(new_lst)