Home Python maps function in Python (with examples)

maps function in Python (with examples)

After applying the supplied function to each item of a given iterable, the map() function returns a map object which is an iterator of the results (list, tuple, etc.)

Historical development of the maps function

Computations in functional programming are performed by mixing functions that receive parameters and return a substantial value (or values). These functions do not change the program’s state or modify its input parameters. They convey the outcome of a calculation. Pure functions are the name given to these types of functions.

Theoretically, applications written functionally will be more accessible to:

  • You to code and use each function separately.
  • You can debug and test specific functions without looking at the rest of the application.
  • You should be aware of this because you will not be dealing with state changes throughout the curriculum.

Functional programming often represents data with lists, arrays, and other iterables and a collection of functions that operate on and alter it. There are at least three regularly used ways for processing data in a functional style:

  • Mapping is applying a transformation function to an iterable to create a new one. The transformation function is called on each item in the original iterable to produce items in the new one.
  • Filtering is the process of generating a new iterable by applying a predicate or a Boolean-valued function on an iterable. It is possible to Filter off any items in the original iterable that cause the predicate function to return false elements in the new iterable.
  • Applying a reduction function to an iterable to obtain a single cumulative result is known as reducing.

However, the Python community demanded some functional programming features in 1993. They wanted the following:

  • Anonymous functions
  • A map() function – is a function that returns a map.
  • filter() function- is a function that allows you to filter data.
  • reduce() function- is a function that reduces the size of an object.

Thanks to a community member’s input, several functional features are introduced to the language. Map(), filter(), and reduce() are now essential components of Python’s functional programming paradigm.

This tutorial will cover one of these functional aspects, the built-in function map(). You’ll also learn to use list comprehensions and generator expressions to achieve the same map() functionality in a Pythonic and legible manner.

Introduction to Python’s map()

You can find yourself in a position where you need to conduct the same action on all of the items in an input iterable to create a new iterable. Using Python for the loop is the quickest and most popular solution to this problem. You may, however, solve this problem without needing an explicit loop by using map().

You’ll learn how the map() works and how to use it to process and change iterables without using a loop in the parts that follow.

map() cycles through the items of an input iterable (or iterables) and returns an iterator that results from applying a transformation function on each item. map() accepts a function object and an iterable (or several iterables) as parameters and returns an iterator that yields transformed objects on-demand, according to the documentation. In a loop, map() applies the function to each item in the iterable, returning a new iterator with modified objects on demand. Any Python function taking the same number of arguments as the number of iterables you send to the map() qualifies. Note that map()’s first argument is a function object, which implies you must pass the function without running it. That is, without the need for a parentheses pair.

The transformation function is the first input to map(). Put another way, it’s the function that turns each original item into a new (transformed) one. Even though the Python documentation refers to this argument function, it can be any Python callable. Built-in functions, classes, methods, lambda, and user-defined functions are all included.

map() is usually a mapping function because it maps every input iterables’ item to a new item in an output iterable; map() does this by applying a transformation function to each item in the input iterable.

The syntax is as follows:

map(fun, iter)

Python’s map() Parameters

fun: It’s a function that a map uses to pass each element of an iterable to. It’s iterable that has to be mapped. The map() function accepts one or more iterables.

Returns: After applying the supplied function to each item of a given iterable, returns a list of the results (list, tuple, etc.) The map() (map object) returned value can then be provided to functions like list() (to build a list) and set() (to construct a set).

Example 1: program demonstrating how the map() function works

# Return double of n
def multiplication(n):
	return n * n

# We double all numbers using map()
num_vals = (3, 4, 5, 6)
result = map(multiplication, num_vals)
print(list(result))
how the map() works
how the map() works

Example 2: Using lambda expression to achieve the results in example 1

We can alternatively engage lambda expressions to achieve the above result with the map.

# Mulitply all numbers using map and lambda
  
num_vals = (3, 4, 5, 6)
result = map(lambda x: x * x, num_vals)
print(list(result))
Using lambda expression
Using lambda expression

Example 3: Using lambda and map

# Add two lists using map and lambda

num_vals_1 = [3, 4, 5]
num_vals_2 = [6, 7, 8]

result = map(lambda x, y: x * y, num_vals_1, num_vals_2)
print(list(result))
using lambda and map
using lambda and map

Example 4: Using the map on lists

# List of strings
laptops = ['HP', 'Dell', 'Apple', 'IBM']

# map() can listify the list of strings individually
result = list(map(list, laptops))
print(result)
 Using the map on lists
Using the map on lists

Example 5: Calculating every word’s length in the tuple:

def funcCalculatingStringLength(n):
  return len(n)

result = map(funcCalculatingStringLength, ('Apple', 'HP', 'Chromebook'))

print(result)
Calculating every word’s length in the tuple:
Calculating every word’s length in the tuple:

Using map() with various function types

With the map, you can use any Python callable (). The callable must take an argument and return a tangible and meaningful value as the only requirement. Classes, instances that implement a specific method called call(), instance methods, class methods, static methods, and functions, for example, can all be used.

The map has several built-in functions that you can use. Think about the following scenarios:

num_vals = [-4, -3, 0, 3, 4]

abs_values = list(map(abs, num_vals))
abs_values


list(map(float, num_vals))

word_lengths = ["Codeunderscored", "is","the" ,"Real", "Deal"]

list(map(len, word_lengths))
using the map with built-in functions

Any built-in function is used with map() as long as it takes an argument and returns a value.

When it comes to utilizing map(), employing a lambda function as the first argument is typical. When passing expression-based functions to map(), lambda functions are helpful. For example, using a lambda function, you may re-implement the example of the square values as follows:

num_vals = [1, 2, 3, 4, 5]

squared_vals = map(lambda num: num ** 2, num_vals)

list(squared_vals)
using map() with lambda
using map() with lambda

Lambda functions are particularly beneficial for using map() (). They can be used as the first argument in a mapping (). You can quickly process and change your iterables using lambda functions with map().

Multiple input iterables processing using a map ()

If you send several iterables to map(), the transformation function must accept the same number of parameters. Therefore, each iteration of the map() passes one value from each iterable to the function as a parameter. The iteration ends when the shortest iterable is reached.

Take a look at the following example, which makes use of pow():

list_one = [6, 7, 8]
list_two = [9, 10, 11, 12]

list(map(pow, list_one, list_two))
Multiple Input Iterables
Multiple Input Iterables

pow() returns x to the power of y given two arguments, x, and y. Using several arithmetic operations, you can merge two or more iterables of numeric values with this technique. The final iterable is limited to the length of the shortest iterable, which in this case is first it. Here are a few examples of how lambda functions are used to do various math operations on multiple input iterables:

list(map(lambda a, b: a - b, [12, 14, 16], [11, 13, 15]))

list(map(lambda p, q, r: p + q + r, [12, 14], [11, 13], [17, 18]))

To combine two iterables of three elements, you perform a subtraction operation in the first example. The values of three iterables are added together in the second case.

Transforming String Iterables using Python’s map()

When working with iterables of string objects, you might want to consider using a transformation function to transform all items. Python’s map() function can come in handy in some instances. The examples in the following sections will show you how to use map() to alter iterables of string objects.

Using the str Methods

Using some of the methods of the class str to change a given string into a new string is a typical technique for string manipulation. If you’re working with iterables of strings and need to apply the same transformation to each one, map() and related string methods can help:

laptops_companies = ["Microsoft", "Google", "Apple", "Amazon"]
list(map(str.capitalize, laptops_companies))

list(map(str.upper, laptops_companies))
list(map(str.lower, laptops_companies))
Using the str Methods
Using the str Methods

You may use map() and string methods to make a few modifications on each item in string it. Most of the time, you’d use methods like str.capitalize(), str.lower(), str.swapcase(), str.title(), and str.upper() that don’t require any additional arguments .

You can also utilize methods that take optional parameters with default values, such str.strip(), which takes an optional argument called char and removes whitespace by default:

laptops_companies = ["Microsoft", "Google", "Apple", "Amazon"]

list(map(str.strip, laptops_companies ))
using map() with strip()
using map() with strip()

A lambda function gives arguments rather than relying on the default value. When you use str.strip() in this way, you depend on the char’s default value. In this scenario, map() removes all whitespace from the with spaces elements. For example, when processing text files, this technique can come in helpful when you need to delete trailing spaces (or other characters) from lines. Keep in mind that removing the newline character with the str.strip() without a custom char will also delete the newline character on the off chance that this is the case.

Using map() in conjunction with other functional tools

So far, you’ve learned how to use map() to perform various iterable-related tasks. You can conduct more complex changes on your iterables if you use map() in conjunction with other functional tools like filter() and reduce(). That’s what the following sections are going to be about.

filter() and map()

You may need to process an input iterable and return another iterable due to removing undesired values from the input iterable. In that instance, Python’s filter() function would be a decent choice. The built-in function filter() accepts two positional arguments:

  • function is a predicate or a Boolean-valued function, which returns True or False depending on the input data.
  • Any Python iterable will be used as iterable.

Filter() utilizes the identity function if you pass None to function. It means that filter() will examine each item in iterable for its truth value and filter out any wrong things. The input iterables items’ for which filter() returns True is returned by filter().

Consider the following scenario: you need to calculate the square root of all the items in a list. You can use map() and filter() to accomplish this. Because the square root isn’t specified for negative numbers, you’ll get an error because your list potentially contains negative values:

import math

math.sqrt(-25)
error getting square root of a negative
error getting the square root of a negative

If the argument is a negative number, math.sqrt() throws a ValueError. To avoid this problem, use filter() to remove any negative numbers and then find the square root of the positive ones that remain. Consider the following scenario:

import math

def chek_if_positive(val):
  return val >= 0

def sanitized_sqrt(nums):
  vals_cleaned = map(math.sqrt, filter(chek_if_positive, nums))
  return list(vals_cleaned)

sanitized_sqrt([64, 16, 49, -25, 4])
filter() and map()
filter() and map()

chek_if_positive() takes a number as an argument and returns True if the number is greater than or equal to zero. To remove all negative values from numbers, send chek_if_positive() to filter(). As a result, map() will only process positive values, and math.sqrt() will not throw a ValueError.

reduce() and map()

Reduce() in Python is a function found in the functools module of the Python standard library. reduce() is a crucial Python functionality that applies a function to an iterable and reduce it to a single cumulative value. Reduction or folding are terms used to describe this type of action. reduce() requires the following two arguments:

  • Any Python callable that takes two arguments and returns a value qualifies as a function.
  • Any Python iterable can be used as iterable.
    reduce() will apply the function to all of the elements in the iterable and compute a final value cumulatively.

Here’s an example of how to use map() and reduce() to compute the total size of all the files in your home directory:

import functools as fn
import operator
import os
import os.path

code_files = os.listdir(os.path.expanduser("~"))
fn.reduce(operator.add, map(os.path.getsize, code_files))

To acquire the path to your home directory, you use the os.path.expanduser(“~”) in this example. Then, on that path, you call os.listdir() to receive a list of all the files that live there.

os.path is used in the map() operation.

To determine the size of each file, use getsize(). To find the total size of all files, use the add() function. Finally, you utilize operator with reduce(). The final result is the home size’s directory in bytes.

Although reduce() can address the problem in this section, Python also has other tools that can help you develop a more Pythonic and efficient solution. To calculate the total size of the files in your home directory, for example, you can use the built-in function sum():

import os
import os.path

underscored_files = os.listdir(os.path.expanduser("~"))
sum(map(os.path.getsize, underscored_files))
size of home directory
size of the home directory

This example is significantly more readable and efficient than the previous one. You can look for further information on Python’s reduce(): From Functional to Pythonic Style, how to use reduce(), and which alternative tools you may use to replace it in a Pythonic fashion.

Processing Iterables(Tuple-Based) with starmap()

Python’s itertools have a function called starmap(). starmap() creates an iterator that applies a function to the arguments in a tuple iterable and returns the results. It comes in handy when working with iterables that have previously been grouped into tuples.

The primary difference between map() and starmap() is that the latter uses the unpacking operator () to unpack each tuple of arguments into many positional arguments before calling its transformation function. As a result, instead of function(arg1, arg2,… argN), the transformation function is called function(args).

According to the official documentation, starmap() is identical to the following Python function:

def starmap(function, iterable):
  for args in iterable:
    yield function(*args)

This function’s for loop iterates through the items in iterable, returning altered objects as a result. In the call to function(*args), the unpacking operator is used to unpack the tuples into many positional arguments. Examples of starmap():

from itertools import starmap

list(starmap(pow, [(7, 12), (9, 8)]))
Processing Iterables with starmap()
Iterables with starmap()

Conclusion

The map() function performs a specified function for each item in an iterable. The item is passed as a parameter to the function. The map() function in Python allows you to process and transform all elements in an iterable without using an explicit for loop, a technique known as mapping. When you need to apply a transformation function to each item in an iterable and change it into a new iterable, map() comes in handy. In Python, map() is one tool that supports functional programming.

You’ve learned how the map() works and how to use it to handle iterables in this tutorial. You also learned about several Pythonic utilities that you can use in your code to replace map().

You may also like

Leave a Comment