Python lambda list comprehensions

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') 
check_num = lambda x: 'Num greater than 5' if x > 5 else 'Num not greater than 5' 

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 

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 

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 

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.

Читайте также:  Java time localdate to instant

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 ?

Источник

Python list comprehension lambda

In this Python tutorial, we will discuss about Python list comprehension.

  • What is Python list comprehension?
  • What is lambda?
  • Lambda function using filter()
  • Lambda function using map()
  • Python list comprehension lambda closure
  • Python list comprehension vs lambda
  • Python list comprehension vs map

What is Python list comprehension?

List comprehension is used to create a new list based on the existing list. The list comprehension is used to work on the list. List comprehension returns the list and It contains expression and brackets.

Syntax for Python list comprehension

[expression for item in list if condition == True]

List comprehension

In this example, I have taken a list as chocolate and if condition is used. Here, the if condition is true. So it returned a new list.

chocolate = ["5star", "silk", "milkybar"] newchocolate_list = [a for a in chocolate if "5" in a] print(newchocolate_list)

You can refer the below screenshot for the output, we can see the new list.

Python list comprehension

Now, we will check what happens if the items are not present in the list. Then, it will return an empty list because the if condition is not true. You can refer to the below screenshot.

Читайте также:  Запретить переворот экрана css

Python list comprehension

What is lambda in Python?

Lambda is a function that is defined without a name. Usually in python functions are defined with a keyword def but anonymous functions are defined by the keyword lambda. The lambda function is used along with the built-in function map(), filter().

In this example, we can see how to find the cube of a given number using lambda function.

cube = lambda a: a * a * a print(cube(5))

In the below screenshot you can see the output:

What is lambda in Python

Python Lambda function using filter()

  • In this example, I have taken a list of numbers and assigned the values from 1 to 12 in it.
  • The filter() function is called with all the items in the list and returns a new list.
  • And then we can use the lambda function using the filter() to get the multiples of 4 from the list.
number = [1,2,3,5,4,6,8,9,11,12] multiples_of_4 = list(filter(lambda a: (a%4 == 0) ,number)) print(multiples_of_4)

Below screenshot shows the output, we can see the multiples of 4 from the list in the output:

Lambda function using filter()

Python Lambda function using map()

  • In this example, I have taken a name of list as numbers and assigned multiples of 5 and each number is divided by 5 using map().
  • The map() is called with all the items in the list and a new list is returned.
number = [5,10,15,20,25,30,35,40,45,50] newnumber = list(map(lambda c: c/5 ,number)) print(newnumber)

You can refer below screenshot for the output:

Lambda function using map()

Python list comprehension lambda closure

  • The closure is used to create resource globally and reuse it in a function to avoid performance issues.
  • Closure can be used only in nested functions. When we call the lambda function it will take the ‘_’ value from the closed namespace.
  • It will not take the ‘_’ value when the lambda object is created. ‘_’ value lives in the namespace.
  • In this example, I have used c = [_() for _ in b]. It works here because a new namespace is used for all the names except the original input.
  • In b = [lambda: _ for _ in a] here I have used different names for loop target.we are not masking over the closed over name.
  • ‘_’ value remains in the namescope and returns the value 4 for 4 times.
a = [1, 2, 3 , 4] b = [lambda: _ for _ in a] c = [_() for _ in b] print(a) print(b) print(c)

Here, In this output we can see last element returns 4 times.

Читайте также:  Get запрос ссылкой php

Python list comprehension lambda closure

Python list comprehension vs lambda

Let us see the difference between Python list comprehension and lambda.

  • List comprehension is used to create a list.
  • Lambda function process is the same as other functions and returns the value of the list.
  • List comprehension is more human-readable than the lambda function.
  • User can easily understand where the list comprehension is used .
  • List comprehension performance is better than lambda because filter() in lambda is slower than list comprehension.

Python list comprehension vs map

Let us try to understand Python list comprehension vs map.

  • List comprehension allows filtering, there is no filtering in the map.
  • List comprehension returns the list of results whereas the map only returns the map objects.
  • The map is faster to call the defined function whereas lambda is not required to call the defined function.
  • Map performance is better comparing to list comprehension.

You may like the following Python tutorials:

  • Python Threading and Multithreading
  • How to Append String to Beginning Of List Python
  • How to convert Python degrees to radians
  • Python Comparison Operators
  • Python namespace tutorial
  • Python Tkinter Frame
  • How to make a matrix in Python
  • How to display a calendar in Python
  • Linked Lists in Python
  • Escape sequence in Python
  • Introduction to Python Interface
  • Python ask for user input

In this Python tutorial, we have learned about the Python list comprehension lambda. Also, We covered these below topics:

  • What is Python list comprehension?
  • What is lambda?
  • Lambda function using filter()
  • Lambda function using map()
  • Python list comprehension lambda closure
  • Python list comprehension vs lambda
  • Python list comprehension vs map

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Оцените статью