What would you do if you wanted to apply a function to each item in an iterable? Your first step would be to use that function by iterating over each item with the for
loop.
Python has a function called map()
that can help you reduce performing iteration stuff and avoid writing extra code.
Python's map() Function
The map()
function in Python is a built-in function that allows you to apply a specific function to each item in an iterable without using a for
loop.
Syntax
map(function, iterable)
function
:map()
applies this function to each item in the iterable.iterable
: list, tuple, string, or iterator object.
The map()
function returns an iterator object containing the result, which can be iterated over to generate values on the fly.
Let's take a closer look at the map()
function with an example.
Example
Consider the following example: a function called add_two()
adds 2 to the argument a
. The map()
function applies the function (add_two()
) to the iterable stored in the variable my_iterable
.
# Function to be applied
def add_two(a):
return a + 2
# List of integers
my_iterable = [34, 23, 45, 10]
# Using map() function
mapping = map(add_two, my_iterable)
result = list(mapping)
print(f"Final result: {result}.")
When you run the above code, you'll get a list in which each element from the original list my_iterable
has been incremented by 2, as specified by the add_two
function.
Final result: [36, 25, 47, 12].
You may be wondering how the function is applied to each item in the iterable without the use of an explicit for
loop. How does themap()
function do it?
How map() Function Works?
You now know that the map()
function applies a function to each item in the iterable, but how exactly does it do so?
Let me explain with an example. How would you apply a function to the items in a list without using the map()
function? You'll use the for
loop to iterate through each item in the list and then apply the function.
# Function to be applied
def add_two(a):
return a + 2
# Empty list to store the final result
final_list = []
# List of integers
my_iterable = [34, 23, 45, 10]
# Using for loop
for item in my_iterable:
result = add_two(item)
final_list.append(result)
print(f"Final result: {final_list}.")
As you can see in the above code, a for
loop is used to iterate through each item in the my_iterable
variable, and within the for
loop, the add_two
function is applied to each item, with the result appended to a list final_list
and printed.
When you run the above code, you will get a similar result as in the first example.
Final result: [36, 25, 47, 12].
That is exactly how the map()
function would have worked in the background for simple operations like the one above.
In fact, you can imitate the map()
function in just one line of code for the above example.
# Function to be applied
def add_two(a):
return a + 2
# List of integers
my_iterable = [34, 23, 45, 10]
# Using list comprehension
mapping = [add_two(item) for item in my_iterable]
print(f"Final result: {mapping}.")
Using the list comprehension in the above code eliminated the need to write the additional lines of code.
Processing Multiple Inputs Using map()
Consider the following scenario: you need to take multiple user inputs and process them using a function. How would you efficiently process the inputs? You can use the map()
function to accomplish your goal.
# Function to convert Fahrenheit to Celcius
def to_celcius(a):
val = (a - 32) * 5/9
return round(val)
# Converting each input item into integer
f_values = list(map(int, input("Enter Temperature(in F): ").split()))
# Applying to_celcius function to each item in the iterable
result = list(map(to_celcius, f_values))
# Displaying the result
print("Result:", result)
The code above accepts multiple user inputs, separated by a space (input().split()
), and the int
function will be applied to each input using map()
before being converted into a list using the list
function.
The next block applies the to_celcius
function to the iterable f_values
and prints the results.
Enter Temperature(in F): 1 100 32 273
Result: [-17, 38, 0, 134]
Using map() with Multiple Iterables
So far, you've only used the map()
function with a single iterable, but the map()
function can accept multiple iterables.
Consider the following example, in which multiple iterables are processed using the map()
function.
def add(x, y):
return x+y
# Iterables
first = [2, 4, 6, 8]
second = [1, 3, 5, 7]
# Both iterables are passed to map()
mapping = list(map(add, first, second))
print(f"Result: {mapping}.")
In the above code, both iterables (first
and second
) and the add
function is passed to the map()
function.
The map()
function iterates each element from both iterable and applies the add
function. The add()
function takes two arguments, x
and y
, and returns the sum of their values. In the first iteration, x
will be 2 and y
will be 1 and the output will be 3 and this will continue till the end of the shortest iterable.
Result: [3, 7, 11, 15].
Using map() with lambda Function
The lambda
expression creates an anonymous function in a single line of code. Using the map()
function and a lambda
expression, you can achieve the desired result in a few lines of code.
first = [2, 4, 6, 8]
second = [1, 3, 5, 7]
# Using lambda expression with map()
mapping = list(map(lambda x, y: x+y, first, second))
print(f"Result: {mapping}.")
The lambda
expression in the code above is the same as the previous section's add
function. Using the lambda
expression eliminates the need to explicitly declare a named function, saving a few lines of code.
The above code will produce the following output.
Result: [3, 7, 11, 15].
Manipulating Iterables of String
Not just integers or floats, the map()
function can be used to transform iterables containing various types of elements, including strings.
words = ["welcome", "to", "geekpython"]
# Converting string to uppercase
uppercase = list(map(str.upper, words))
print(f"Result: {uppercase}.")
# Capitalizing string
capitalize = list(map(str.capitalize, words))
print(f"Result: {capitalize}.")
The map()
function is used in the above code to apply the str.upper
and str.capitalize
functions to the words
variable (a list of strings). When you run it, you will notice that the strings are transformed.
Result: ['WELCOME', 'TO', 'GEEKPYTHON'].
Result: ['Welcome', 'To', 'Geekpython'].
You can also perform various other operations by declaring a function. For instance, you can declare a function to reverse the strings or slice out some parts from the string.
words = ["welcome", "to", "geekpython"]
# Reverses a string
def reverse(string):
return string[: : -1]
rev = list(map(reverse, words))
print(f"Reversed: {rev}.")
# Slices a string
def custom_slice(string):
return string[1: 3: 1]
slice_string = list(map(custom_slice, words))
print(f"Sliced: {slice_string}.")
Output
Reversed: ['emoclew', 'ot', 'nohtypkeeg'].
Sliced: ['el', 'o', 'ee'].
Conclusion
In simple terms, the map()
function maps a function to each item in an iterable and returns an iterator object. This iterator can be looped over or converted into a data type, such as a list.
In this article, you've learned:
What is the
map()
function and how to use it?How
map()
works and imitating themap()
function usingfor
loop and list comprehension.Processing multiple user inputs using
map()
.Processing multiple iterable using
map()
.Using
lambda
expression withmap()
to eliminate creating a named function.Manipulating iterable containing string items.
๐Other articles you might be interested in if you liked this one
โ Serialize and deserialize Python objects using the pickle module.
โ How to use pytest to test your Python code?
โ Create a WebSocket server and client in Python.
โ Create multi-threaded Python programs using a threading module.
โ Create and integrate MySQL database with Flask app using Python.
โ Upload and display images on the frontend using Flask.
That's all for now
Keep Codingโโ
Top comments (0)