Lambda, Map, Filter and Sorted - Efficient Programming With Python

This is very useful to use lambda in anonymous function in Python. An anonymous function is a function without a name. But Don’t get me wrong. Lambda can be used in a function with a name as well. I love using lambda because it makes the program looks very concise and still clear and understandable. In addition, it doesn’t make your program slow. Here is the syntax:

lambda x,…. : expression

I put few dots after x to symbolize some more arguments. Lambda can take any number of arguments but only one expression. Let’s see some use cases.

Here is a function that takes one argument x and returns x squared.

def squared(x):
     return x*x

Now write this same function using lambda.

squared = lambda x: x*x

Both the squared function works exactly the same way. Now see a simple addition function where function takes two arguments:

add = lambda x, y: x+y

#Calling the function add

add(4, 5)

output: 9

Map

Map function in Python takes lists and a function and returns the list, modified by the function. Let’s work on some examples. Here are three lists a, b and c.

a = [3,4,5,2,7,8]

b = [7,9,2,4,5,1]

c = [5,7,3,4,5,9]

Call the add function on lists a and b

add(a,b)

output: [3, 4, 5, 2, 7, 8, 7, 9, 2, 4, 5, 1]

This doesn’t give an elementwise addition. Our add function adds numbers the way it should. But when it comes to lists, it just makes a bigger lists with all the elements of both the lists in it. Typically, the way we do elementwise addition is by using for loop. Something like this:

res = []

for i in range(0, len(a)):

    res.append(a[i]+ b[i])

res

Using ‘map’, you can call this add function on lists a and b to get element-wise addition. It works just like a for loop.  

list(map(add, a, b))

Isn’t it lot more concise and elegant?

It’s even better to use lambda and map together. You can define the function and call it at the same time in one line of code.

list(map(lambda x, y: x+y, a, b))

In fact, you can add all three of the lists or as many arguments as you want:

list(map(lambda x, y, z: x+y+z, a, b, c))

Instead of just adding if you have a formula using three agruments:

list(map(lambda x, y, z: 2*x + 2.5*y + z, a, b, c))

Filter

Filter takes a list as argument and a function as the expression. It returns the modified list after filtering out the elements by the function. Here are some examples. 

Return only the number bigger than 5 in a list.

list(filter(lambda x: x>5, c))

Here I passed c as the argument. Return only the even numbers from a list. This time I am going to pass list a.

list(filter(lambda x: x%2==0, a))

All the examples above are with numbers. Next few example will be on strings. Here is a list of names:

names = [‘Abram’, ‘Arib’, ‘Bob’, ‘Shawn’, ‘Aria’, ‘Cicilia’, ‘John’, ‘Reema’, ‘Alice’, ‘Craig’, ‘Aaron’, ‘Simi’]

Return all the names that start will ‘A’.

list(filter(lambda x: x[0]!=’A’, names))

Sorted

Sorted function is a very simple, easy way of sorting numbers or strings by alphabets. Some examples are here:

Sort the names of the list above by the first letter.

sorted(names, key=lambda x: x[0])

output: 

[‘Abram’, ‘Arib’, ‘Aria’, ‘Alice’, ‘Aaron’, ‘Bob’, ‘Cicilia’, ‘Craig’, ‘John’, ‘Reema’, ‘Shawn’, ‘Simi’]

It works. But even better option is:

sorted(names)

Output:

[‘Aaron’, ‘Abram’, ‘Alice’, ‘Aria’, ‘Arib’, ‘Bob’, ‘Cicilia’, ‘Craig’, ‘John’, ‘Reema’, ‘Shawn’, ‘Simi’]

In this way, the names get sorted by alphabetic order. The same thing works for lists as well.

sorted(c)

Output:

[3, 4, 5, 5, 7, 9]

Lambda, Map, Filter and Sorted With Dictionaries

Working with dictionaries are far easier and efficient with lambda, map, filter and sorted.

Here is a list that has four dictionaries. Each dictionary consists of the name of a person and his or her age.

dict_a = [{‘name’: ‘John’, ‘age’: 12},

         {‘name’: ‘Sonia’, ‘age’: 10},

         {‘name’: ‘Steven’, ‘age’: 13},

         {‘name’: ‘Natasha’, ‘age’: 9}]

Return the list of only names from the list above:

list(map(lambda x: x[‘name’], dict_a))

Output: [‘John’, ‘Sonia’, ‘Steven’, ‘Natasha’]

The same way, you can output the age only from dict_a:

list(map(lambda x: x[‘age’], dict_a))

If you want the names to be sorted by alphabets or the list of ages to be sorted, simply put a sorted before:

sorted(list(map(lambda x: x[‘age’], dict_a)))

Output: [9, 10, 12, 13]

Probably, you think, it’s more useful to arrange the whole dict_a sorted by ages. In that case, we just need to use key with lambda:

sorted(dict_a, key=lambda x: x[‘age’])

Output: 

[{‘name’: ‘Natasha’, ‘age’: 9}, 

{‘name’: ‘Sonia’, ‘age’: 10}, 

{‘name’: ‘John’, ‘age’: 12}, 

{‘name’: ‘Steven’, ‘age’: 13}]

Output the youngest child’s information:

sorted(dict_a, key=lambda x: x[‘age’])[0]

Output: {‘name’: ‘Natasha’, ‘age’: 9}

Output the oldest child’s information:

sorted(dict_a, key=lambda x: x[‘age’])[-1]

Output: {‘name’: ‘Steven’, ‘age’: 13}

Instead of ascending order if we need the list to be in descending order:

sorted(dict_a, key=lambda x: x[‘age’], reverse =True)

Output: 

[{‘name’: ‘Steven’, ‘age’: 13}, 

{‘name’: ‘John’, ‘age’: 12}, 

{‘name’: ‘Sonia’, ‘age’: 10}, 

{‘name’: ‘Natasha’, ‘age’: 9}]

Or, if you want to sort by the names in alphabetic order:

sorted(dict_a, key=lambda x: x[‘name’])

Output the information of the children who are older than 10:

list(filter(lambda x: x[‘age’]>10, dict_a))

Output:

[{‘name’: ‘John’, ‘age’: 12},

{‘name’: ‘Steven’, ‘age’: 13}]

After three years you are returning the ages of the kids. So, just just add 3 to each age:

list(map(lambda x: x[‘age’]+3, dict_a))

Output: [15, 13, 16, 12]

Hope this was helpful. Please stay with this website for more educational article. 

#Python #programming #pythonprogramming #lambda #sorting

Leave a Reply

Close Menu