Python Intermediate_002_Map Function
Introduction
The map() function is a powerful tool in Python for applying a function to every item in an iterable, streamlining code and enhancing readability. In this tutorial, we’ll explore the map() function through practical examples, from basic to advanced use cases. Additionally, we’ll conclude with a problem that leverages map() to solve a real-world coding challenge, demonstrating its utility in concise and efficient solutions.
What is the map() function?
The map() function in Python is used to apply a given function to all items in an iterable (like a list, tuple, etc.). This function returns a map object (which is an iterator), which you can convert into a list, tuple, or any other iterable.
Get CodeAddict’s stories in your inbox
Join Medium for free to get updates from this writer.
The power of map() is in its ability to simplify applying the same operation to multiple items in an iterable without needing to write explicit loops.
Syntax of the map() Function
map(function, iterable, ...)- function: A function that you want to apply to each item of the iterable(s).
- iterable: One or more iterables (lists, tuples, etc.) whose items will be processed by the function.
- If multiple iterables are passed, the function must take as many arguments as there are iterables.
Example 1: Simple Example
# Define a simple function that doubles a number
def double(x):
return x * 2
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Use map to apply 'double' to each item in the list
doubled_numbers = map(double, numbers)
# Convert the result to a list and print it
print(list(doubled_numbers))
# Output: [2, 4, 6, 8, 10]Explanation:
- We define a function
double(x)that multiplies the input by 2. - The
map()function appliesdouble()to each item in thenumberslist. - The result is a map object, which we convert to a list for easier viewing. The output will be
[2, 4, 6, 8, 10].
Example 2: Using Lambda
Now, let’s use a lambda function to achieve the same result. This will make the code shorter and more concise.
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Use map with a lambda function to double the numbers
doubled_numbers = map(lambda x: x * 2, numbers)
# Convert the result to a list and print it
print(list(doubled_numbers))
# # Output: [2, 4, 6, 8, 10]Explanation:
- Instead of defining a separate function, we use a lambda function
lambda x: x * 2directly in themap(). - This reduces the code and makes it more compact while still achieving the same result.
Example 3: Multiple Iterables
In this example, we’ll work with two lists and apply a function that adds corresponding elements from each list.
# Function to add corresponding elements from two lists
def add(x, y):
return x + y
# Two lists of numbers
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
# Use map to add corresponding elements of numbers1 and numbers2
sum_numbers = map(add, numbers1, numbers2)
# Convert the result to a list and print it
print(list(sum_numbers))
# Output: [5, 7, 9]Explanation:
- The function
add(x, y)adds two numbers together. - We pass two lists,
numbers1andnumbers2, to themap()function. - The
map()function applies theadd()function to the elements of both lists, adding corresponding elements together. The result is[5, 7, 9].
Problem: Finding the kth Number in Sliced and Sorted Arrays
To solidify your understanding of the map() function, let’s apply it to a practical problem.
Problem Description
You need to find the kth number in a sliced and sorted portion of an array. Specifically, for an array and a set of commands, each command [i, j, k] instructs you to:
- Slice the array from the i-th to the j-th position (1-based indexing).
- Sort the sliced array in ascending order.
- Return the k-th number (1-based indexing) from the sorted slice.
For example:
- Given the array [1, 5, 2, 6, 3, 7, 4] and a command [i=2, j=5, k=3]:
- Slice from the 2nd to the 5th position: [5, 2, 6, 3].
- Sort the slice: [2, 3, 5, 6].
- The 3rd number is 5.
Given an array and a two-dimensional array commands containing multiple [i, j, k] commands, return an array of results for all commands.
Restrictions
- The length of array is between 1 and 100.
- Each element in array is between 1 and 100.
- The length of commands is between 1 and 50.
- Each command in commands is a list of length 3.
Solution
Here’s a concise solution using the map() function with a lambda:
def solution(array, commands):
return list(map(lambda x: sorted(array[x[0]-1:x[1]])[x[2]-1], commands))Solution Explanation
- The map() function applies a lambda function to each command x in commands.
- For each command x = [i, j, k]:
- array[x[0]-1:x[1]] slices the array from index i-1 to j (adjusting for 0-based indexing).
- sorted(…) sorts the sliced array.
- [x[2]-1] selects the k-th element (adjusting for 0-based indexing).
- The map() result is converted to a list, yielding the final array of results.
- This solution is concise and leverages map() to avoid explicit loops, making it both efficient and readable.
Other Solutions:
def solution(array, commands):
return [sorted(array[i-1:j])[k-1] for i, j, k in commands]Or:
def solution(array, commands):
answer = []
for com in commands:
arr = sorted(array[com[0]-1:com[1]])
answer.append(arr[com[2]-1])
return answer
array = [1, 5, 2, 6, 3, 7, 4]
commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
solution(array, commands)






