Open In App

Python lambda

Last Updated : 05 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

n Python, an anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.

Python lambda Syntax:

lambda arguments : expression

Python lambda Example:

Python3




calc = lambda num: "Even number" if num % 2 == 0 else "Odd number"
 
print(calc(20))


Output:

Even number

Python lambda properties:

  • This function can have any number of arguments but only one expression, which is evaluated and returned.
  • One is free to use lambda functions wherever function objects are required.
  • You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
  • It has various uses in particular fields of programming, besides other types of expressions in functions.

Example 1: Program to demonstrate return type of Python lambda keyword 

Python3




string = 'GeeksforGeeks'
 
# lambda returns a function object
print(lambda string: string)


Output

<function <lambda> at 0x7fd7517ade18>

Explanation: In this above example, the lambda is not being called by the print function, but simply returning the function object and the memory location where it is stored. So, to make the print to print the string first, we need to call the lambda so that the string will get pass the print.

Example 2: Invoking lambda return value to perform various operations

Here we have passed various types of arguments into the different lambda functions and printed the result generated from the lambda function calls.

Python3




filter_nums = lambda s: ''.join([ch for ch in s if not ch.isdigit()])
print("filter_nums():", filter_nums("Geeks101"))
 
do_exclaim = lambda s: s + '!'
print("do_exclaim():", do_exclaim("I am tired"))
 
find_sum = lambda n: sum([int(x) for x in str(n)])
print("find_sum():", find_sum(101))


Output:

filter_nums(): Geeks
do_exclaim(): I am tired!
find_sum(): 2

Example 3: Difference between lambda and normal function call

The main difference between lambda function and other functions defined using def keyword is that, we cannot use multiple statements inside a lambda function and allowed statements are also very limited inside lambda statements. Using lambda functions to do complex operations may affect the readability of the code.

Python3




def cube(y):
    print(f"Finding cube of number:{y}")
    return y * y * y
 
 
lambda_cube = lambda num: num ** 3
 
# invoking simple function
print("invoking function defined with def keyword:")
print(cube(30))
# invoking lambda function
print("invoking lambda function:", lambda_cube(30))


Output:

invoking function defined with def keyword:
Finding cube of number:30
27000
invoking lambda function: 27000

Example 4: The lambda function gets more helpful when used inside a function.

We can use lambda function inside map(), filter(), sorted() and many other functions. Here, we have demonstrated how to use lambda function inside some of the most common Python functions.

Python3




l = ["1", "2", "9", "0", "-1", "-2"]
# sort list[str] numerically using sorted()
# and custom sorting key using lambda
print("Sorted numerically:",
      sorted(l, key=lambda x: int(x)))
 
# filter positive even numbers
# using filter() and lambda function
print("Filtered positive even numbers:",
      list(filter(lambda x: not (int(x) % 2 == 0 and int(x) > 0), l)))
 
# added 10 to each item after type and
# casting to int, then convert items to string again
print("Operation on each item using lambda and map()",
      list(map(lambda x: str(int(x) + 10), l)))


Output

Sorted numerically: ['-2', '-1', '0', '1', '2', '9']
Filtered positive even numbers: ['1', '9', '0', '-1', '-2']
Operation on each item using lambda and map() ['11', '12', '19', '10', '9', '8']

using mylist:

In this example, we define a lambda function that takes an argument x and adds 10 to it. We then use the map() function to apply the lambda function to each element in the list my_list. Finally, we convert the result to a list and print it.

Here’s another example that uses a lambda function to filter out even numbers from a list:

Python3




# Example list
my_list = [1, 2, 3, 4, 5]
 
# Use lambda to filter out even numbers from the list
new_list = list(filter(lambda x: x % 2 != 0, my_list))
 
# Print the new list
print(new_list)


Output

[1, 3, 5]

Approach:

Define a list ‘my_list’ with some numbers.
Use lambda function with filter to check whether a number in the list is even or not.
Convert the filter object into a list using the list() function and store it in a new_list.
Print the new list with odd numbers.
Time Complexity:
The time complexity of the filter function is O(n) where n is the number of elements in the list. The lambda function does not affect the time complexity, as it is a simple check that takes constant time.

Space Complexity:
The space complexity of this code is O(n) because it creates a new list that contains only odd numbers from the original list. The original list is not modified, so it remains the same size.



Previous Article
Next Article

Similar Reads

Python: Iterating With Python Lambda
In Python, the lambda function 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, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Lambda and filter in Python Examples
Prerequisite : Lambda in Python Given a list of numbers, find all numbers divisible by 13. Input : my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70] Output : [65, 39, 221] We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is witho
2 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time &amp; constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv
1 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Overuse of lambda expressions in Python
What are lambda expressions? A lambda expression is a special syntax to create functions without names. These functions are called lambda functions. These lambda functions can have any number of arguments but only one expression along with an implicit return statement. Lambda expressions return function objects. For Example consider the lambda expr
8 min read
Using lambda in GUI programs in Python
Python Lambda Functions are anonymous function means that the function is without a name. In this article, we will learn to use lambda functions in Tkinter GUI. We use lambda functions to write our code more efficiently and to use one function many times by passing different arguments. We use the lambda function to pass arguments to other functions
3 min read
Difference between List comprehension and Lambda in Python
List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
3 min read
Python | Find fibonacci series upto n using lambda
The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1. Find the series of fibonacci numbers using lambda function. Code #1 : B
2 min read
Practice Tags :