Site icon Meccanismo Complesso

Python Lessons – 6.3 Map and Filter

Python lessons - 6.3 Map and Filter m
Python lessons - 6.3 Map and Filter

Map

In Python, there is a built-in function, called map(), which can be very useful for high-order functions that operate on lists. In fact, this function takes a function and an iterable object (such as a list) as arguments, and returns a new iterable object (such as a new list) with the function applied for each argument.

In the case of lists you must always use the list() function that creates a new list

def increase(x):
    return x + 1

lista = [2,6,12,3,5]
res = list(map(increase,lista))
print(res) 

if you run it, you get

>>>
[3, 7, 13, 4, 6]

The same operation could have been codified more simply using the lambda syntax, since the function is simple (it can be expressed in a single line) and it is therefore not necessary to define it, but to use it only at the moment.

lista = [2,6,12,3,5]
res = list(map(lambda x: x+1,lista))
print(res)   

Filter

Another very useful function that works on iterables is the filter () function. This function filters an iterable object by selecting only the elements that respond to a given predicate. (The predicate is a function that returns a Boolean).

lista = [2,6,12,3,5]
res = list(filter(lambda x: x > 5,lista))
print(res) 

if you run it, you get

>>>
[6, 12]

⇐ Go to Python Lesson 6.2 – Lambda Functions

Go to Python Lesson 6.4 – Generators ⇒

Exit mobile version