Python Programming

Python Map() function with example code fully explained

Python Map() function, Overview:

Python map() is a built-in function that permits you to measure and change all the things in an iterable without utilizing an express for loop, a strategy is normally known as mapping. map() is valuable when you have to apply a change function to everything in an iterable and change them into another iterable. map() is one of the apparatuses that help a functional programming style in Python.

In this tutorial, you’ll learn:

  • How Python map() works
  • How to change various kinds of Python iterables utilizing map()
  • How to join map() with other functional devices to perform more intricate changes
  • What instruments you can use to supplant map() and make your code more Pythonic

With this information, you’ll have the option to utilize map() successfully in your projects or, on the other hand, to utilize list understandings or generator articulations to make your code more Pythonic and comprehensible.

For a superior comprehension of python map(), some past information on the best way to work with iterables, for loops, functions, and lambda functions would be useful.


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Coding With Functional Style in Python

In functional programming, calculations are finished by joining functions that take contentions and return a solid worth (or qualities) subsequently. These functions don’t alter their info contentions and don’t change the program’s state. They simply give the consequence of a given calculation. These sorts of functions are normally known as unadulterated functions.

In principle, programs that are built utilizing a functional style will be simpler to:

  • Develop in light of the fact that you can code and utilize each function in disconnection
  • Debug and test since you can test and troubleshoot singular functions without taking a gander at the remainder of the program
  • Understand in light of the fact that you don’t have to manage state changes all through the program

Functional programming normally utilizes records, clusters, and different iterables to speak to the information alongside a bunch of functions that work on that information and change it. With regards to preparing information with a functional style, there are at any rate three ordinarily utilized strategies:

  1. Mapping comprises applying a change function to an iterable to create another iterable. Things in the new iterable are created by calling the change function on everything in the first iterable.
  2. filtering involves applying a predicate or Boolean-regarded function to an iterable to make another iterable. Things in the new iterable are made by filtering out any things in the primary iterable that make the predicate function return sham.
  3. Reducing comprised of applying a decrease function to an iterable to deliver a solitary combined worth.

As indicated by Guido van Rossum, Python is more firmly impacted by basic programming dialects than functional dialects:

I have never believed Python to be vigorously impacted by functional dialects, regardless of what individuals state or think. I was considerably more acquainted with basic dialects, for example, C and Algol 68 and in spite of the fact that I had made functions top notch objects, I didn’t see Python as a functional programming language. (Source)

Notwithstanding, in 1993, the Python people group was requesting some functional programming highlights. They were requesting:

  • Anonymous functions
  • A python map() function
  • A filter() function
  • A reduce() function

These functional highlights were added to the language because of the commitment of a network part. These days, map(), filter(), and reduce() are central segments of the functional programming style in Python.

In this tutorial, you’ll cover one of these functional highlights, the built-in function map(). You’ll additionally figure out how to utilize list cognizances and generator articulations to get a similar functionality of map() in a Pythonic and decipherable way.

Beginning With Python map() function

Here and there you may confront circumstances in which you have to play out similar procedure on all the things of an information iterable to manufacture another iterable. The snappiest and most regular way to deal with this issue is to utilize a Python for loop. Nonetheless, you can likewise handle this issue without an express loop by utilizing map().

In the accompanying three areas, you’ll figure out how map() works and how you can utilize it to measure and change iterables without a loop.



Getting map()

map() loops over the things of an info iterable (or iterables) and restores an iterator that outcomes from applying a change function to each thing in the first information iterable. As indicated by the documentation, map() takes a function object and an iterable (or numerous iterables) as contentions and returns an iterator that yields changed things on request. The function’s mark is characterized as follows:

map(function, itera[, itera1, itera2,…, iteraN])

map() applies function to everything in iterable in a loop and returns another iterator that yields changed things on request. function can be any Python function that takes a number of contentions equal to the number of iterables you pass to map().

This first argument to map() is a change function. At the end of the day, the function changes every unique item into another (changed) item. Despite the fact that the Python documentation calls this argument function, it very well may be any Python callable. This incorporates built-in functions, classes, methods, lambda functions, and user-defined functions.

The operation that map() performs is generally known as a mapping since it maps each item in an information iterable to another item in a subsequent iterable. To do that, map() applies a change function to all the items in the info iterable.

To more readily get map(), assume you have to take a rundown of numeric values and change it into a rundown containing the square estimation of each number in the first rundown. For this situation, you can utilize a for loop and code something like this:

>>> numbers = [1, 2, 3, 4, 5]
>>> squared = []
>>> for num in numbers:
...     squared.append(num ** 2)
...
>>> squared
[1, 4, 9, 16, 25]

At the point when you run this loop on numbers, you get a rundown of square values. The for loop emphasizes over numbers and applies a force operation on each worth. At last, it stores the subsequent values in squared.

You can accomplish a similar outcome without utilizing an explicit loop by utilizing map(). Investigate the accompanying reimplementation of the above model:

>>> def square(number):
...     return number ** 2
...

>>> numbers = [1, 2, 3, 4, 5]
>>> squared = map(square, numbers)
>>> list(squared)
[1, 4, 9, 16, 25]

square() is a change function that maps a number to its square esteem. The call to map() applies square() to the entirety of the values in numbers and returns an iterator that yields square values. At that point you call list() on map() to make a list object containing the square values.

Since map() is written in C and is profoundly advanced, its inward inferred loop can be more productive than a standard Python for loop. This is one bit of leeway of utilizing map().

A second preferred position of utilizing map() is identified with memory utilization. With a for loop, you have to store the entire list in your framework’s memory. With map(), you get items on request, and just one item is in your framework’s memory at a given time.

For another model, say you have to change over all the items in a list from a string to an integer number. To do that, you can utilize map() alongside int() as follows:

>>> str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"]
>>> int_nums = map(int, str_nums)
>>> int_nums
<map object at 0x7fb2c7e34c70>
>>> list(int_nums)
[4, 8, 6, 5, 3, 2, 8, 9, 2, 5]
>>> str_nums
["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"]

map() applies int() to each incentive in str_nums. Since map() restores an iterator (a map object), you’ll need call list() with the goal that you can deplete the iterator and transform it into a list object. Note that the first grouping doesn’t get changed all the while.


Utilizing python map() With Different Kinds of Functions

You can utilize any sort of Python callable with map(). The main condition would be that the callable takes an argument and returns a solid and helpful worth. For instance, you can utilize classes, cases that execute a unique technique called call(), occurrence methods, class methods, static methods, and functions.

There are some built-in functions that you can use with map(). Think about the accompanying models:

>>> numbers = [-2, -1, 0, 1, 2]
>>> abs_values = list(map(abs, numbers))
>>> abs_values
[2, 1, 0, 1, 2]
>>> list(map(float, numbers))
[-2.0, -1.0, 0.0, 1.0, 2.0]
>>> words = ["Welcome", "to", "Real", "Python"]
>>> list(map(len, words))
[7, 2, 4, 6]

You can utilize any built-in function with map(), given that the function takes an argument and returns a worth.

A typical example that you’ll see with regards to utilizing map() is to utilize a lambda function as the primary argument. lambda functions are helpful when you have to pass an articulation based function to map(). For instance, you can reimplement the case of square values utilizing a lambda function as follows:

>>> numbers = [1, 2, 3, 4, 5]
>>> squared = map(lambda num: num ** 2, numbers)
>>> list(squared)
[1, 4, 9, 16, 25]

lambda functions are very valuable with regards to utilizing map(). They can assume the function of the main argument to map(). You can utilize lambda functions alongside map() to rapidly measure and change your iterables.

Handling Multiple Input Iterables With python map()

On the off chance that you flexibly multiple iterables to map(), at that point the change function must take the same number of arguments as iterables you pass in. Every emphasis of map() will pass one incentive from each iterable as an argument to function. The emphasis stops toward the finish of the most brief iterable.

Consider the accompanying model that utilizes pow():

>>> first_it = [1, 2, 3]
>>> second_it = [4, 5, 6, 7]
>>> list(map(pow, first_it, second_it))
[1, 32, 729]

pow() takes two arguments, x and y, and returns x to the power of y. In the principal iterations, x will be 1, y will be 4, and the outcome will be 1. In the subsequent emphasis, x will be 2, y will be 5, and the outcome will be 32, etc. The last iterable is just as long as the most brief iterable, which is first_it for this situation.

This strategy permits you to blend at least two iterables of numeric values utilizing various types of math operations. Here are a few models that utilization lambda functions to perform distinctive math operations on a few input iterables:

>>> list(map(lambda x, y: x - y, [2, 4, 6], [1, 3, 5]))
[1, 1, 1]
>>> list(map(lambda x, y, z: x + y + z, [2, 4], [1, 3], [7, 8]))
[10, 15]

In the first example, you utilize a deduction operation to combine two iterables of three items each. In the subsequent model, you include the values of three iterables.


Changing Iterables of Strings With Python map()

At the point when you’re working with iterables of string objects, you may be interested in changing all the items utilizing some sort of change function. Python map() can be your partner in these circumstances. The accompanying segments will walk you through certain instances of how to utilize map() to change iterables of string objects.

Utilizing the Methods of str

A very basic way to deal with string manipulation is to utilize a portion of the methods of the class str to change a given string into another string. In case you’re managing iterables of strings and need to apply a similar change to each string, at that point you can utilize map() alongside different string methods:

>>> string_it = ["processing", "strings", "with", "map"]
>>> list(map(str.capitalize, string_it))
['Processing', 'Strings', 'With', 'Map']
>>> list(map(str.upper, string_it))
['PROCESSING', 'STRINGS', 'WITH', 'MAP']
>>> list(map(str.lower, string_it))
['processing', 'strings', 'with', 'map']

There are a couple of changes that you can perform on each item in string_it utilizing map() and string methods. More often than not, you’d use methods that don’t take additional arguments, as str.capitalize(), str.lower(), str.swapcase(), str.title(), and str.upper().

You can likewise utilize a few methods that take additional arguments with default esteems, for example, str.strip(), which takes a discretionary argument considered singe that defaults to eliminating whitespace:

>>> with_spaces = ["processing ", "  strings", "with   ", " map   "]
>>> list(map(str.strip, with_spaces))
['processing', 'strings', 'with', 'map']

At the point when you use str.strip() like this, you depend on the default estimation of roast. For this situation, you use map() to eliminate all the whitespace in the items of with_spaces.

>>> with_dots = ["processing..", "...strings", "with....", "..map.."]
>>> list(map(lambda s: s.strip("."), with_dots))
['processing', 'strings', 'with', 'map']

This procedure can be convenient when, for example, you’re preparing text records in which lines can have following spaces (or different characters) and you have to eliminate them. If so, at that point you have to consider that utilizing str.strip() without a custom singe will eliminate the newline character also.

Removing Punctuation

With regards to preparing text, you now and then need to eliminate the punctuation denotes that stay after you split the content into words. To manage this issue, you can make a custom capacity that eliminates the punctuation marks from a solitary word utilizing a regular expression that coordinates the most well-known punctuation marks. Here’s a potential execution of this capacity utilizing sub(), which is a regular expression work that lives in the re module in Python’s standard library:

>>> import re
>>> def remove_punctuation(word):
...     return re.sub(r'[!?.:;,"()-]', "", word)
>>> remove_punctuation("...Python!")
'Python'

Inside remove_punctuation(), you utilize a regular expression design that coordinates the most well-known punctuation denotes that you’ll discover in any content written in English. The call to re.sub() replaces the coordinated punctuation marks utilizing an unfilled string (“”) and returns a cleaned word.


Changing Iterables of Numbers With Python map():

map() additionally has incredible potential with regards to handling and changing iterables of numeric values. You can play out a wide assortment of math and number-crunching tasks, convert string values to floating-point numbers or integer numbers, etc.

In the accompanying areas, you’ll cover a few instances of how to utilize map() to measure and change iterables of numbers.

Utilizing Math Operations Using Python Map():

A typical case of utilizing math activities to change an iterable of numeric values is to utilize the power operator (**). In the accompanying model, you code a change function that takes a number and returns the number squared and cubed:

>>> def powers(x):
...     return x ** 2, x ** 3
...
>>> numbers = [1, 2, 3, 4]
>>> list(map(powers, numbers))
[(1, 1), (4, 8), (9, 27), (16, 64)]

powers() takes a number x and returns its square and 3D shape. Since Python handles different return values as tuples, each call to powers() restores a tuple with two values. At the point when you call map() with powers() as an argument, you get a rundown of tuples containing the square and the shape of each number in the info iterable. There are a great deal of math-related changes that you can perform with map(). You can add constants to and take away them from each value. You can likewise utilize a few functions from the numerical module like sqrt(), factorial(), sin(), cos, etc. Here’s a model using factorial():

>>> import math
>>> numbers = [1, 2, 3, 4, 5, 6, 7]
>>> list(map(math.factorial, numbers))
[1, 2, 6, 24, 120, 720, 5040]

For this situation, you change numbers into another list containing the factorial of each number in the first list.

You can play out a wide range of math changes on an iterable of numbers using map(). How far you get into this subject will rely upon your necessities and your creative mind. Think about it and code your own models!

Converting Temperatures

Another utilization case for map() is to change over between units of measure. Assume you have a list of temperatures estimated in degrees Celsius or Fahrenheit and you have to change over them into the relating temperatures in degrees Fahrenheit or Celsius.

You can code two change functions to achieve this errand:

def to_fahrenheit(c):
    return 9 / 5 * c + 32
def to_celsius(f):
    return (f - 32) * 5 / 9

to_fahrenheit() takes a temperature estimation in Celsius and makes the change to Fahrenheit. Likewise, to_celsius() takes a temperature in Fahrenheit and converts it to Celsius.

These functions will be your change functions. You can utilize them with map() to change over an iterable of temperature estimations to Fahrenheit and to Celsius individually:

>>> celsius_temps = [100, 40, 80]
>>> # Convert to Fahrenheit
>>> list(map(to_fahrenheit, celsius_temps))
[212.0, 104.0, 176.0]
>>> fahr_temps = [212, 104, 176]
>>> # Convert to Celsius
>>> list(map(to_celsius, fahr_temps))
[100.0, 40.0, 80.0]

In the event that you call map() with to_fahrenheit() and celsius_temps, at that point you get a list of temperature measures in Fahrenheit. In the event that you call map() with to_celsius() and fahr_temps, at that point you get a list of temperature measures in Celsius.

To expand this model and cover some other sort of unit change, you simply need to code a fitting change function.



Converting Strings to Numbers using Python map():

When working with numeric information, you’ll probably manage circumstances in which all your information are string values. To do any further estimation, you’ll have to change over the string values into numeric values. map() can help with these circumstances, as well.

In case you’re certain that your information is spotless and doesn’t contain wrong values, at that point you can utilize drift() or int() legitimately as indicated by your necessities. Here are a few models:

>>> # Convert to floating-point
>>> list(map(float, ["12.3", "3.3", "-15.2"]))
[12.3, 3.3, -15.2]
>>> # Convert to integer
>>> list(map(int, ["12", "3", "-15"]))
[12, 3, -15]

In the main model, you use skim() with map() to change all the values from string values over to floating-point values. In the subsequent case, you use int() to change over from a string to an integer. Note that in the event that one of the values is certifiably not a legitimate number, at that point you’ll get a ValueError.

In the event that you don’t know that your information is spotless, at that point you can utilize a more intricate transformation function like the accompanying:

>>> def to_float(number):
...     try:
...         return float(number.replace(",", "."))
...     except ValueError:
...         return float("nan")
...

>>> list(map(to_float, ["12.3", "3,3", "-15.2", "One"]))
[12.3, 3.3, -15.2, nan]

Inside to_float(), you utilize an attempt articulation that gets a ValueError if drift() bombs when converting number. In the event that no mistake happens, at that point your function returns number changed over to a legitimate floating-point number. Else, you get a nan (Not a Number) value, which is an exceptional buoy value that you can use to speak to values that aren’t substantial numbers, much the same as “One” in the above model.

You can tweak to_float() as indicated by your necessities. For instance, you can supplant the assertion return float(“nan”) with the assertion return 0.0, etc.

Combining map() With Other Functional Tools

Up until this point, you’ve covered how to utilize map() to achieve various errands involving iterables. Notwithstanding, in the event that you use map() alongside other functional tools like filter() and reduce(), at that point you can perform more mind boggling changes on your iterables. That is what you’re going to cover in the following two areas.

map() and filter()

Some of the time you have to deal with an input iterable and return another iterable that outcomes from filtering out undesirable values in the input iterable. All things considered, Python’s filter() can be a decent choice for you. filter() is a built-in work that takes two positional contentions:

  1. capacity will be a predicate or Boolean-esteemed capacity, a capacity that profits True or False according to the input information.
  2. iterable will be any Python iterable.

filter() yields the things of the input iterable for which capacity brings True back. On the off chance that you pass None to work, at that point filter() utilizes the personality work. This implies that filter() will check reality estimation of everything in iterable and filter out the entirety of the things that are falsy.

To represent how you can utilize map() alongside filter(), say you have to figure the square root of the apparent multitude of values in a list. Since your list can contain negative values, you’ll get an error on the grounds that the square root isn’t defined for negative numbers:

>>> import math

>>> math.sqrt(-16)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    math.sqrt(-16)
ValueError: math domain error

With a negative number as a contention, math.sqrt() raises a ValueError. To maintain a strategic distance from this issue, you can utilize filter() to filter out all the negative values and afterward find the square root of the remaining positive values. Look at the following model:

>>> import math
>>> def is_positive(num):
...     return num >= 0
...
>>> def sanitized_sqrt(numbers):
...     cleaned_iter = map(math.sqrt, filter(is_positive, numbers))
...     return list(cleaned_iter)
...
>>> sanitized_sqrt([25, 9, 81, -16, 0])
[5.0, 3.0, 9.0, 0.0]

is_positive() is a predicate work that accepts a number as a contention and returns True if the number is more prominent than or equal to zero. You can pass is_positive() to filter() to eliminate all the negative numbers from numbers. Along these lines, the call to map() will deal with just positive numbers and math.sqrt() won’t give you a ValueError.


map() and reduce()

Python’s reduce() is a capacity that lives in a module called functools in the Python standard library. reduce() is another center functional tool in Python that is helpful when you have to apply a capacity to an iterable and reduce it to a single aggregate worth. This kind of activity is ordinarily known as decrease or folding. reduce() takes two required contentions:

  1. function can be any Python callable that acknowledges two contentions and returns a worth.
  2. iterable can be any Python iterable.

reduce() will apply capacity to all the things in iterable and aggregately process a final worth.

Here’s a model that combines map() and reduce() to figure the complete size of the apparent multitude of documents that live in your home registry aggregately:

>>> import functools
>>> import operator
>>> import os
>>> import os.path
>>> files = os.listdir(os.path.expanduser("~"))
>>> functools.reduce(operator.add, map(os.path.getsize, files))
4377381

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button