In this tutorial, we will delve into one of Python’s built-in functions, the
map() function. This powerful tool can simplify your code and make it more efficient.
What is the map() Function?
map() function in Python takes in two or more arguments: a function and one or more iterables, in the form:
map(function, iterable, ...)
This function returns an iterator that applies the given function to every item of the iterable(s), yielding the results.
How to Use map()
map(), you need to define a function that specifies the logic for each element in your iterable. Then pass this function as an argument along with your iterable into
def square(n): return n * n numbers = [1, 2, 3, 4] result = map(square, numbers) print(list(result)) # Output: [1, 4, 9, 16]
In this example above, we defined a simple function called ‘square’ that multiplies a number by itself. We then used
map(), passing in our ‘square’ function and our list of numbers. The result is a new list where each number has been squared.
Lambda Functions with map()
You can also use lambda functions with
map(). Lambda functions are small anonymous functions that are not bound to any name. They allow you to write quick throwaway functions without needing to formally define them.
numbers = [1, 2, 3, 4] result = map(lambda x: x * x, numbers) print(list(result)) # Output: [1, 4, 9, 16]
In this example above, we used a lambda function to square each number in our list. The result is the same as our previous example.
Multiple Iterables with map()
map() function can also handle multiple iterables. It will apply its function to the elements of the input iterables in parallel. With multiple iterables,
map() stops when the shortest iterable is exhausted.
numbers1 = [1, 2, 3] numbers2 = [4, 5, 6] result = map(lambda x,y: x + y , numbers1,numbers2) print(list(result)) # Output: [5,7,9]
In this example above we passed two lists into
map(), along with a lambda function that adds two numbers together. The result is a new list where corresponding elements from each list have been added together.
map() function is a powerful tool for applying a function to every item in an iterable(s). It can simplify your code and make it more efficient by eliminating explicit loops over the iterable(s).