DEV Community

suvhotta
suvhotta

Posted on

Python: Lambda and List Comprehension

Imagine in a parallel universe, video game Super Mario had a different ending - He wouldn't have to fight, rather he would have to code. To make it even further spicy, in the final level of the game, One line of correct code and Mario could take the princess back.

Of course Mario is up for the challenge with Python's Lambda expressions and List Comprehension in his arsenal.

Both Lambda Expression and List Comprehension can be handy while dealing with too many loops within the code.

Lambda Expression:

If you're conceptually clear with Python functions, then half of your job is already done because Lambda Expressions are nothing but shorthand representation of Python functions.

Let's take a simple example of writing a function to check if a number is greater than 5.

What a coding Newbie would do:

def check_num(num):
    if(num > 5):
      print('Number is greater than 5')
    else:
      print('Number isn't greater than 5')
Enter fullscreen mode Exit fullscreen mode

What an experienced coder would do:

check_num = lambda x: 'Num greater than 5' if x > 5 else 'Num not greater than 5'
Enter fullscreen mode Exit fullscreen mode

The general syntax of a Python Lambda is
lambda arguments : expression

The return value of the lambda function is the value that this expression is evaluated to.

Lambdas are mostly useful when you're dealing with functions that will be used only once in the program, or anonymous functions.

One can make most out of these Lambda expressions by using it with map or filter functions.

map():

Syntax:
map(func,iterables)
map() passes each element in the iterable through a function and returns the result of all elements having passed through the function.

func is the function which would be applied on each element present in iterables.

The return type of map() function is a list in python 2. However in python 3 it is a map object. To get a list, built-in list() function can be used : list(map(func,iterables))

Combining map and Lambda:
Suppose we've a mundane task of increasing all the elements of a list by 3 units.

num_list = [2,3,4,5,6]
increased = list(map(lambda x: x+3 , num_list))
increased
Enter fullscreen mode Exit fullscreen mode

Output:
[5,6,7,8,9]

Here the lambda expression is the function paramter to map().

filter():

Syntax:
filter(func,iterables)

As the name suggests, filter() will give a filtered sequence from those elements of iterable for which function returns True.

Combining filtered and Lambda:
Filtering out a list of odd numbers from a given list:

num_list = [2,3,4,5,6]
odd_num = list(filter(lambda x: x%2!=0 , num_list))
odd_num
Enter fullscreen mode Exit fullscreen mode

Output:
[3,5]

List Comprehension:

Syntax:
[ expression for item in list if condition ]

List Comprehension provides a brief way to create lists. It starts and end with '[' and ']' , which notifies that this is a list.

Squaring even numbers from a list of numbers:

num_list = [2,3,4,5,6]
sq_list = [x*x for x in num_list if x%2==0]
sq_list
Enter fullscreen mode Exit fullscreen mode

Output:
[4,16,36]

You might have known by now that there are stuffs which can be achieved by combining map() and Lambda Expressions and also by List Comprehensions.

When to use What?

If we are calling an already defined function then map() is a bit faster than the corresponding List Comprehension.

But when evaluating any other expression,List Comprehension is faster and clearer than map(), because the map incurs an extra function call for each element.

Some people prefer List Comprehension as they say it is a more pythonic and systematic way of coding.

But then people are free to have their Opinions aren't they ?

Top comments (0)