map()

Introduction

map is a higher-order function , used in many programming languages, which applies some function to each element of the list of its arguments, returning a list of results as the return value.

The function map() returns a map object which is iterable, after applying the given function to each object in the given iterable object ( list , tuple, etc.)

In simple words - if there is some list and some function - map() can apply this function to all elements of the list, and write what the function returns into a new list.

Syntax

map(function, iterable)

Example

The simplest example of applying the multiply-by-2 function

l1 = [1, 2, 3] def mult2(x): return x*2 m = map(mult2, l1) print(m) print(list(m))

<map object at 0x7f57a016ff40> [2, 4, 6]

Checking a list

To check whether all numbers in a list are positive you need to use the function all() as well as, for example, map() and lambda

l1 = [1, 2, 3] l2 = [1, -2, "some text"] if all(map(lambda x: x > 0, l2)): print("all positive in l2") else: print("not all positive in l2") if all(map(lambda x: x > 0, l1)): print("all positive in l1") else: print("not all positive in l1")

all positive in l1
not all positive in l2

Your own map()

Perhaps the work of the map() function will become clearer if you try to write your own analog

def square(x): return x * x def my_map(func, arg_list): result = [] for i in arg_list: result.append(func(i)) return result squares = my_map(square, [1, 2, 3, 4, 5]) print(squares)

python custom_map.py

[1, 4, 9, 16, 25]

Article author: Andrei Olegovich

Banner image