Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
How to use if, else & elif in Python Lambda Functions
Next article icon

In Python, thelambdafunction is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python.

Syntax:

lambda variable : expression

Where,

  1. variable is used in the expression
  2. expression can be an mathematical expression

Example 1:

 In the below code, We make for loop to iterate over a list of numbers and find the square of each number and save it in the list. And then, print a list of square numbers.

Python3
# Iterating With Python Lambdas# list of numbersl1=[4,2,13,21,5]l2=[]# run for loop to iterate over listforiinl1:# lambda function to make square# of numbertemp=lambdai:i**2# save in list2l2.append(temp(i))# print listprint(l2)

Output:

[16, 4, 169, 441, 25]

Example 2:

We first iterate over the list using lambda and then find the square of each number. Here map function is used to iterate over list 1. And it passes each number in a single iterate. We then save it to a list using the list function. 

Python3
# Iterating With Python Lambdas# list of numbersl1=[4,2,13,21,5]# list of square of numbers# lambda function is used to iterate# over list l1l2=list(map(lambdav:v**2,l1))# print listprint(l2)

Output:

[16, 4, 169, 441, 25]

Example 3:

In the below code, we use map, filter, and lambda functions. We first find odd numbers from the list using filter and lambda functions. Then, we do to the square of it using map and lambda functions as we did in example 2.

Python3
# Iterating With Python Lambdas# list of numbersl1=[4,2,13,21,5]# list of square of odd numbers# lambda function is used to iterate over list l1# filter is used to find odd numbersl2=list(map(lambdav:v**2,filter(lambdau:u%2,l1)))# print listprint(l2)

Output:

[169, 441, 25]

Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp