0
0
Pythonprogramming~5 mins

map() function in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the map() function do in Python?
The map() function applies a given function to each item of an iterable (like a list) and returns a map object with the results.
Click to reveal answer
beginner
How do you convert the result of map() into a list?
You can convert the map object to a list by using the list() function, like list(map(function, iterable)).
Click to reveal answer
intermediate
Can map() work with multiple iterables? If yes, how?
Yes, map() can take multiple iterables. The function you provide must accept as many arguments as there are iterables. It applies the function to items from all iterables in parallel.
Click to reveal answer
beginner
What type of object does map() return?
map() returns a map object, which is an iterator that generates the results on demand.
Click to reveal answer
intermediate
Why is map() useful compared to a for-loop?
map() is useful because it can make code shorter and clearer by applying a function to all items without writing an explicit loop. It also can be more memory efficient since it returns an iterator.
Click to reveal answer
What does map(str, [1, 2, 3]) return?
AAn error because str is not a list
BA list of strings ['1', '2', '3']
CA string '123'
DAn iterator that converts each number to a string
How do you apply a function to two lists element-wise using map()?
AUse a for-loop only
BUse <code>map(function(list1, list2))</code>
CUse <code>map(function, list1, list2)</code>
DUse <code>map(function, [list1, list2])</code>
What happens if the iterables passed to map() have different lengths?
AThe function continues until the longest iterable is exhausted
BThe function stops when the shortest iterable is exhausted
CAn error is raised
DThe shorter iterable is repeated
Which of these is a correct way to get a list of squares from [1, 2, 3] using map()?
Alist(map(lambda x: x**2, [1, 2, 3]))
Bmap(lambda x: x**2, [1, 2, 3])
Clist(map([1, 2, 3], lambda x: x**2))
Dmap([1, 2, 3]**2)
Is the following statement true or false?
"map() immediately applies the function to all items and stores the results in memory."
AFalse
BTrue
COnly if the iterable is a list
DOnly if the function is built-in
Explain how the map() function works and give a simple example.
Think about how you can change each item in a list without a loop.
You got /3 concepts.
    Describe how you can use map() with multiple lists and what happens if they have different lengths.
    Imagine pairing items from two lists and applying a function to each pair.
    You got /3 concepts.