Iterating with Python Lambda

Learn how to iterate with Python lambda? By IncludeHelp Last updated : December 30, 2023

In Python programming language, an anonymous function i.e., a function without a name and lambda keyword is known as the Lambda function. Lambda function is used as a function object. Here, we will learn how to iterate the elements with lambda function?

Syntax for iterating with Python Lambda

Here, is the syntax to be used to iterate with lambdas,

lambda variable : expression

Here,

  • variable - It is used in the given expression
  • expression - The expression to be evaluated with each element.

Iterating with Lambda (Example 1)

In the below example, there is a list of integer numbers, we will iterate its elements and find the cubes of all elements with lambda.

# Python program to demonstrate the example to
# iterate with lambda
  
# list of integers
numbers = [10, 15, 20, 25, 30]

# list to store cubes
cubes = []
  
# for loop to iterate over list
for x in numbers:
    # lambda expression to find cubes
    res = lambda x:x**3
    # appending to the list (cubes)
    cubes.append(res(x))
  
# print the lists
print("numbers:", numbers)
print("cubes:", cubes)

Output

numbers: [10, 15, 20, 25, 30]
cubes: [1000, 3375, 8000, 15625, 27000]

Iterating with Lambda (Example 2)

In the below example, there is a list of integer numbers, we will iterate its elements and find the cube of all even elements with lambda, map(), and filter() functions.

# Python program to demonstrate the example to
# iterate with lambda
  
# list of integers
numbers = [10, 15, 20, 25, 30]

# finding cubes of even numbers 
# and storing them into cubes
cubes = list(map(lambda x: x**3, filter(lambda y: y%2==0, numbers)))
  
# print the lists
print("numbers:", numbers)
print("cubes:", cubes)

Output

numbers: [10, 15, 20, 25, 30]
cubes: [1000, 8000, 27000]

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.