Python map() Function, Explained with Examples

On this tutorial you’ll learn to use the Python map() operate to use a operate to all gadgets of an iterable.

Python helps the practical programming paradigm that permits you to outline duties as a programmatic computation of features. You may deal with Python features like objects: a operate can take one other operate as a parameter and return one other operate.

The map() operate takes a operate as an argument and allows you to apply it to all gadgets in a sequence.

On the finish of this tutorial it is possible for you to to make use of Python map() operate – to rewrite prolonged loops and enumerate ideas. You code a number of examples to grasp the other ways you should use the map() operate.

How one can apply a operate to components of a Python checklist

Apply a function to elements of a Python list

Let’s begin our dialogue with an instance.👩‍🏫

Right here nums is a listing of numbers.

nums = [2,4,3,7]

Subsequent, take into account the operate self_pow(). The operate self_pow() takes a quantity as an argument and returns the quantity raised to the ability of the quantity itself: n**n.

In Python, ** is the exponentiation operator. a**b returns the worth of a raised to the ability of b, aB.

def self_pow(n):
  return n**n

TO DO: to create a brand new checklist nums_pow by making use of the operate self_pow() for every ingredient within the checklist nums.

Use for loop

To do that, you should use for loops in Python:

  • For any quantity within the nums checklist, name the operate self_pow() of num as an argument.
  • Add the results of the operate name to the brand new checklist nums_pow.
nums_pow = []

for num in nums:
  nums_pow.append(self_pow(num))

print(nums_pow)

Within the output any quantity nums is elevated to itself. The weather in it nums_pow checklist is as follows: 224433.77.

Output
[4, 256, 27, 823543]

Use checklist comprehension

You may make this concise utilizing checklist comprehension. From the specific for loop above, we will determine the output expression and the checklist we have to loop by means of.

python-map-function-motivation

We will then modify the overall expression for checklist comprehension:

new_list = [<output expression> for item in iterable]

The checklist comprehension expression for the nums_pow checklist is as follows:

nums_pow = [self_pow(num) for num in nums]
print(nums_pow)

The output is identical as anticipated from utilizing for loops.

Output
[4, 256, 27, 823543]

As an alternative of loop and checklist comprehension, you should use Python map() operate with a concise syntax that helps apply the operate to all gadgets in an iterable. Let’s begin studying the map operate syntax.

Python map() Operate syntax

Python map() Function syntax

The final syntax for utilizing the Python map() operate is as follows:

map(operate, iterable_1,[iterable_2,...,iterable_n])

The map() takes up operate not less than two arguments, a operate and a iterable.

Within the syntax above:

  • operate denotes a Python operate or, generally, any Python callable. This contains user-defined and built-in features, courses, occasion and sophistication strategies, and extra.
  • iterable is any legitimate Python iterable, corresponding to a listing, tuple, and string.
  • The map() operate adjusts the operate Disagreeable every article within the iterable

What does the map() operate return?

It returns a map object. You may then solid the map object to a listing utilizing the syntax: checklist(map(operate,iterable)).

Relying on the use case, you possibly can solid it in a Python tuple.

What does the map() function return?

Now that you’ve got discovered Python syntax map() operate, let’s begin coding examples.

It is best to have Python 3.x to observe this tutorial. In any other case, you possibly can run the code snippets within the Geekflare on-line Python editor.

How one can use the map() operate with user-defined features

Use the map() function with user-defined functions

#1. We used to have the self_pow() operate for any quantity within the nums checklist. Within the syntax for map() operate, we will go the operate self_pow and the checklist nums because the arguments.

Comment: You will need to specify solely the identify of the operate and never a operate name. Utilization self_pow and never self_pow().

The map() operate returns a map object.

print(map(self_pow,nums))

<map object at 0x7f7d315c14d0>

We will then checklist the map object utilizing the checklist() operate, as proven beneath.

nums_pow = checklist(map(self_pow,nums))
print(nums_pow)

Right here is the output the place each num in nums is assigned to quantitynum in nums_pow checklist.

Output
[4, 256, 27, 823543]

#2. Think about the next operate inch_to_cm() converts inches to centimeters. 1 inch = 2.54 cm.

def inch_to_cm(inch):
  return inch*2.54

To vary the inch values ​​within the inches checklist in centimeters, you should use the map() operate as proven within the code cell beneath.

inches = [5.54,3.4,1,25,8.2]
cms = checklist(map(inch_to_cm,inches))
print(cms)

The cms checklist incorporates the inch values ​​expressed in centimeters.

Output
[14.0716, 8.636, 2.54, 63.5, 20.828]

How one can use the map() operate with built-in features

Use the map() function with built-in functions

On this part, we’ll learn to use it map() with built-in features in Python.

#1. The checklist strings is a listing of programming languages. You need to create a brand new checklist strings_upper which incorporates the uppercase programming language strings.

strings = ['JavaScript','Rust','Python','Go']

The built-in string technique .higher() operates on a string and returns an uppercase copy.

strings_upper = checklist(map(str.higher,strings)) 
print(strings_upper)

The checklist strings_upper incorporates strings within the checklist strings formatted in capital letters.

Output
['JAVASCRIPT', 'RUST', 'PYTHON', 'GO']

#2. The built-in len() operate in Python takes a string as an argument and returns its size. To measure the size of every of the strings within the strings checklist, we will use the map() operate and apply the size operate to every string as proven beneath.

strings_len = checklist(map(len,strings))
print(strings_len)
Output
[10, 4, 6, 2]

#3. You should utilize the map() operate with different units corresponding to tuples.

The next instance incorporates a tuple with details about the variety of bedrooms, the world and town wherein a home is situated.

In Python, the kind() operate returns the information kind of every Python object. To get the datatype of all gadgets on this tuple you should use the map() operate to kind operate on every tuple merchandise.

home = (2,758.5,'Bangalore')
house_elt_type = tuple(map(kind,home))
print(house_elt_type)

We have now solid the map object right into a tuple. It’s also possible to solid into a listing or one other assortment.

Within the output beneath, we see that the information kinds of 2, 758.5 ​​and Bangalore are derived as ‘int’, ‘float’ and ‘str’ respectively.

Output
(<class 'int'>, <class 'float'>, <class 'str'>)

#4. In Python, you possibly can import built-in modules and use the features outlined within the modules.

To calculate the sq. root of any quantity within the nums checklist, you should use the sq. root operate sqrt from the mathematics module.

import math
nums = [30,90,34,45,97]
nums_sqrt = checklist(map(math.sqrt,nums))
print(nums_sqrt)
Output
[5.477225575051661, 9.486832980505138, 5.830951894845301, 6.708203932499369, 9.848857801796104]

The above output is tough to parse and observe. You might need to spherical every sq. root worth, for instance, to 2 decimal locations.

How one can Spherical a Floating Level Quantity in Python

Let’s outline a operate round_2() the place a floating level worth is taken and it’s rounded to 2 decimal locations.

def round_2(num):
  return spherical(num,2)

Now you possibly can map() operate with the round_2 and the nums_sqrt checklist.

nums_sqrt_round = checklist(map(round_2,nums_sqrt))
print(nums_sqrt_round)
Output
[5.48, 9.49, 5.83, 6.71, 9.85]

It’s also possible to use nested map() features, the place the inside map operate is used to calculate the sq. root checklist nums_sqrtand the outer map operate performs the rounding operation.

nums_sqrt_round = checklist(map(round_2,checklist(map(math.sqrt,nums))))
print(nums_sqrt_round)
Output
[5.48, 9.49, 5.83, 6.71, 9.85]

The outputs are similar in each approaches above. Nevertheless, you could be certain that the code is readable and maintainable when nesting features as proven above.

How one can use the map() operate with Lambda features

Use the map() function with Lambda functions

Within the earlier sections you discovered how you can use Python map() characteristic with built-in and user-defined features. You’ll now learn to use the map() operate with lambda features, that are nameless in Python.

Generally you will have a operate whose physique incorporates just one line of code, and chances are you’ll solely want to make use of the operate as soon as and never reference it wherever else in this system. You may outline features as lambda operate in Python.

Comment:lambda args: expression is the overall syntax for utilizing a Python lambda operate.

#1. Think about the next checklist strings. As an example you need to obtain a listing strings_rev – with an inverted copy of every of the strings.

strings = ['JavaScript','Rust','Python','Go']

We will reverse a Python string utilizing string slicing.

Comment: This can be a generalization of the string slicing expression str[start:stop:step].

– With out the begin And cease values, the section begins initially of the string and extends to the tip of the string.
– Detrimental values ​​of step returns slices from the tip of the string.
– Subsequently, str[::-1] returns a reversed copy of str.

You should utilize this lambda operate: lambda x:x[::-1]Inside the map operate, as proven beneath.

strings_rev = checklist(map(lambda x:x[::-1],strings))
print(strings_rev)

As with different examples, we place the map object in a listing. Within the output, we see that every of the strings within the checklist strings is reversed.

Output
['tpircSavaJ', 'tsuR', 'nohtyP', 'oG']

#2. Within the earlier part, we calculated the sq. root of every quantity within the quantity checklist after which rounded every sq. root worth to 2 decimal locations.

We have now used the operate round_2() to do that. Let’s rewrite the round_2() operate as a lambda operate and use with the map() operate described beneath.

nums_sqrt_round_l =checklist(map(lambda num:spherical(num,2),nums_sqrt))
print(nums_sqrt_round_l)

As proven beneath, the output is similar to what we obtained utilizing the round_2() operate.

Output
[5.48, 9.49, 5.83, 6.71, 9.85]

How one can use the map() operate with a number of iterables

Use the map() function with multiple iterables

Within the examples we have seen, we have utilized a operate to all gadgets of precisely one iterable.

Generally we have now features that take two or extra arguments. On this case, every argument is saved in a listing or related assortment.

We will additionally use the Python map() operate with a number of lists.

#1. Think about the next operate space() that accepts the size And breadth as enter and returns the world, size*breadth.

def space(size,breadth):
  return size*breadth

The size and width of various rectangles are saved in two separate lists, lengths And breadthsrespectively.

lengths = [4,8,10,18]
breadths = [9,4,6,11]

We will use the map() operate to use the world operate to the above lists by utilizing each the lengths And breadths lists.

areas = checklist(map(space,lengths,breadths))
print(areas)

As a result of the operate space accepts two arguments, the latitude and longitude values ​​from the lists are used lengths breadthsrespectively.

Output
[36, 32, 60, 198]

#2. The Python math module has the log operate that enables us to calculate the logarithm of a quantity with any base.

Comment: log(x, base) returns the worth of log x to the bottom specified by the worth base, log base X. If the bottom shouldn’t be specified, the default base worth is e (log calculates the pure logarithm).

On this instance:

  • The checklist x corresponds to the values ​​for which you need to calculate the logarithm.
  • The base checklist incorporates all base values ​​for use within the logarithm calculation.
x = [2,6,12,10]
base = [2,3,2,5]

We will use the Python map() operate with math.logthe lists, x And base to get the brand new checklist log_xas follows.

log_x = checklist(map(math.log,x,base))
print(log_x)

This is the output.

Output
[1.0, 1.6309297535714573, 3.5849625007211565, 1.4306765580733933]

Conclusion

This is a abstract of what you discovered on this tutorial:

  • The Python operate map() takes not less than two arguments: a operate and an iterable, with the syntax map(operate, iterable(s)).
  • The operate might be any legitimate callable Python.
  • When the operate takes in ok arguments, use the map() operate with the operate and every of the ok arguments in an iterable.

Subsequent, be taught to work with units in Python. Additionally learn to use the Python sleep operate.

Leave a Comment

porno izle altyazılı porno porno