List Comprehensions, lambda, filter, map and reduce functions in Python

For a complete newbie, using these functions is not usual, unless they discover about them one day.
Well this post is intended to make readers get their hands down and dirty with all of these.

List Comprehensions

To start with, List comprehension provide a “shorthand” way to create lists.
Didn’t get me? 
Ohk, how will you print 10 numbers starting from 0 in the form of a list? You would do something like this.

>>>my_list = []
>>>for i in range(10):

Seems very easy and you may have done or seen this numerous times.
What if I did this..

>>>my_list = [i for i in range(10)]

Feels fresh? Certainly yes and looks more “Pythonic” too.

Although the code which you typed in initially wasn't wrong, but then this one adds more beauty to the code.

Hmm, so Let’s look up some more code which will show you the power of list comprehensions.

Printing the cube of all numbers in a list starting from 1 to 10.

>>> output_list = [i**3 for i in range(1,11)]
>>> print output_list
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Printing all the names in the list in lowercase.

>>> output_list = [i.lower() for i in [“RAHUL”,”LAKHANPAL”]]
>>> print output_list
[‘rahul’, ‘lakhanpal’]

Apart from doing simple operations, we can do a lot more.
Suppose we wanted to use conditionals on list, yeah the same if else blocks?

Print all the odd numbers of a list starting from 2 to 12.

>>> output_list = [i for i in range(2,13) if i%2==0]
>>> print output_list
[2, 4, 6, 8, 10, 12]

Pretty Easy!
Ohk, now lets move on to the Complex stuff.

Many a times, you would have a data structure which will be like a lists of lists. or in other terms a Nested List Comprehension.
For instance,

my_list = [[1,2],[3,4],[5,6],[7,8]]

And we want to have this flattened, or in another terms open up the list.
Again without using list comprehensions,

>>>final_list = []
>>>for i in mylist:
for j in i:
>>> print final_list
[1, 2, 3, 4, 5, 6, 7, 8]

Going back to what we learned in list comprehensions, we would do something of this sort.

>>>my_list = [[1,2],[3,4],[5,6],[7,8]]
>>>final_list = [j for i in my_list for j in i]
>>>print final_list
[1, 2, 3, 4, 5, 6, 7, 8]

The expression [j for i in my_list for j in i] can be broken down as:
[value for inner_list in outer_list for value in inner_list]

Now that we have made ourselves comfortable with List comprehensions, we are ready to move towards our main topics.

lambda functions

These are the functions which we can generate on the fly and are inline functions with ready-to-use capability.

Unlike the usual function syntax, which uses “def” to define a function, here we use lambda.
Let’s see a few examples.

>>>#Function to print the squares of any number
>>> my_function = lambda x: x**2
>>> my_function(10)
>>>#Function to print True is number greater than 10 
>>> my_function = lambda x: “True” if x>10 else “False”
>>> my_function(10)

filter(),map() and reduce()

All these 3 functions follow a similar kind of syntax in terms of arguments they take.

For instance, the first parameter is a list and the second parameter is a function that has to be applied over every iterable on that list.
Lets walk through an example.

my_list = [0,1,2,3,4,5,6]

map() function maps the function call on every element of the list.
Here map() applies the function lambda x: x+1 on my_list elements,which increments each element by 1.
The output is always a list of the same length as of the parent list.

>>> map(lambda x: x+1,my_list)
[1, 2, 3, 4, 5, 6, 7]

filter() function does the same but the difference being that it filters out those elements which satisfy a specific condition.
Here lambda x: x>2 and x<5 function takes in only those values out from my_list which satisfy the given criteria.Again the result is a list with elements equal to or less than the original list.

>>> filter(lambda x: x>2 and x<5,my_list)
[3, 4]

reduce() function behaves differently in a way that it just outputs a single numerical value.Here it applies the lambda function which takes 2 values and adds them.

>>> reduce(lambda x,y: x+y,my_list)

This additions happens in this manner.
0+1 = 1
1+2 = 3
3+4 = 7
7+5 = 12
12+7 = 21

So, you see, the sum of first two digits is added to the third in the list in this case.

The function reduce() was moved to functools module in Python 3.

Hope the above article was useful and explanatory to an extent.

Happy Coding!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.