Python Lambda Functions

A lambda function is a function without a name i.e. an anonymous function. The keyword lambda is used to define a lambda function in Python and has only a single expression.

Syntax of Lambda Functions

lambda arguments: expressions

The lambda function can have any number of arguments, but only one expression.

Examples of Lambda Functions

The following are some of the examples of the usage of Lambda Functions:

Example 1 – Multiplying a number by an argument with Python Lambda

Demo80.py

# Multiplying a number to an argument with Python Lambda

val = lambda i: i*2 # creates an anonymous function (a function without a name)
print(val(25))

'''
The anonymous function takes one parameter i and returns i*2
This function is assigned to the variable val
'''

# or, add in a single line
(lambda i: (print(i*2)))(25)

Output

50
50

Example 2 – Perform string operations with Python Lambda Functions

In this example, we will declare a string and display it with Lambda Functions.

Demo81.py

# String operations with Python Lambda

str = "Hello World"

# uppercase
(lambda s: print(s.upper()))(str)

# length
(lambda s: print("Length = ",len(s)))(str)

# display the first and last characters
(lambda s: (print(s[0]),print(s[-1])))(str)

# display the string twice
(lambda s: (print(s),print(s)))(str)

Output

HELLO WORLD
Length =  11
H
d
Hello World
Hello World

We have performed various string operations above. Let us understand them one by one:

  1. Uppercase Conversion
    A lambda function is defined: (lambda s: print(s.upper()))
    It takes one argument s and prints it in uppercase using .upper().
    Then it’s immediately called with str → prints HELLO WORLD.
  2. Length of String
    Lambda takes s and prints its length using len(s).
    "Hello World" has 11 characters (including the space).
    Output: Length = 11
  3. First and Last Characters
    Lambda prints the first character s[0] and the last character s[-1].
    For "Hello World":

    • First character → H
    • Last character → d
  4. Display String Twice
    Lambda prints the strings twice.

Example 3 – Lambda Functions with more than two arguments

In this example, we will multiply 3 arguments with lambda functions.

Demo82.py

# Multiplying 3 arguments with lambda
val = lambda i, j, k : i * j * k

# Display multiplication result of 3 arguments
print("Result = ",val(10, 20, 30))

Output

Result =  6000

Example 4 – Find the maximum of two numbers with Lambda Functions

In this example, we will use the if-else statement to display the maximum of two given numbers.

Demo83.py

# finding the maximum number
res = lambda i, j : i if(i > j) else j
 
# displaying the result
print("Maximum = ",res(50, 100))

Output

Maximum =  100

Example 5 – Find the square of a number with Python Lambda Functions

Demo84.py

# find square of a number
val = lambda i: i*i

# display the result
print("Result (square) = ",val(9))

Output

Result (square) =  81

Examples of Lambda with Python Built-in Functions

Here are some key built-in functions:

map() function

The map() function allows you to apply a given function to each item in one or more iterables (like lists, tuples, or sets). Instead of writing a loop, map() provides a concise way to transform data element by element.

The following is the syntax:

map(function, iterable, ...)

Here,

  • function: The function to apply to each element.
  • iterable: One or more iterables whose elements will be processed.

Example 1: Lambda with map() (Single Iterable)

Let us see an example to square each number in a list:

numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared)) 

Output

[1, 4, 9, 16]

Here, the lambda function squares each number in the list.
According to the syntax:

function → lambda x: x**2

This is the function that will be applied to each element of the iterable. In this case, it takes an input x and returns x**2 (the square of x), which is raised to the power of 2, i.e., squaring.

iterable → numbers (which is [1, 2, 3, 4])

This is the sequence of values that map() will process one by one. Each element of the numbers is passed into the lambda function.

So, step by step:

  1. Take the first element 1 → apply lambda x: x**2 → result 1.
  2. Take the second element 2 → apply function → result 4.
  3. Take the third element 3 → result 9.
  4. Take the fourth element 4 → result 16.

Finally, map() returns an iterator with these results, which we convert into a list: [1, 4, 9, 16]

Example 2: Lambda with map() (Multiple Iterables)

Let us see an example to add corresponding elements of two lists using map() with lambda.

The lambda function takes two arguments, so map() processes elements from both lists in parallel.

# Lambda with Python Built-in function map()  (Multiple Iterables)

a = [1, 2, 3]
b = [4, 5, 6]

result = map(lambda x, y: x + y, a, b)
print(list(result))

Output

[5, 7, 9]

Step-by-Step Explanation

  1. Two Lists (Iterables):
    • a = [1, 2, 3]
    • b = [4, 5, 6]

    These are the sequences that map() will process in parallel.

  2. Function:
    • lambda x, y: x + y
    • This anonymous function takes two arguments (x from list a and y from list b) and returns their sum.
  3. map() Execution:
    • map() pairs elements from a and b one by one:
      • First pair: x=1, y=41+4 = 5
      • Second pair: x=2, y=52+5 = 7
      • Third pair: x=3, y=63+6 = 9
  4. Result:
    • map() produces an iterator with values [5, 7, 9].
    • Converting it to a list with list(result) makes the output visible.

Example 3: Lambda with map() (Single Iterable)

Let us see an example to triple each element of a list

Here, each element is multiplied by 3.

# Lambda with Python Built-in function map() (Single Iterable)
# Example 3

mylist = [10, 20, 30, 40]

# map object
res = map(lambda x: x*3, mylist)

# converting map to list
print(list(res))

Output

[30, 60, 90, 120]

Example 4: Lambda with map() (Single Iterable)
Let us see an example to convert strings to uppercase:

# Lambda with Python Built-in function map() (Single Iterable)
# Convert strings to uppercase

words = ["cricket", "football"]

# map object
res = map(lambda s: s.upper(), words)

# converting map to list
print(list(res))

Output

['CRICKET', 'FOOTBALL']

Example 5: Lambda with map() (Single Iterable)
Let us see an example to extract First Character of Strings:

# Lambda with Python Built-in function map() (Single Iterable)
# Example 5
# Extract First Character of Strings

names = ["Steve", "Charlie", "David"]

# map object
res = map(lambda s: s[0],names)

# converting map to list
print(list(res))

Output

['S', 'C', 'D']

filter() function

The filter() function is a built-in Python function used to filter elements from an iterable (like a list, tuple, or string) based on a condition. A lambda function is often used with filter() because it allows writing short, inline conditions.

It takes two arguments:

  1. A function (usually returns True or False).
  2. An iterable (like a list).

The following is the syntax

filter(function, iterable)

Here,

  • function → A function that tests each element (returns True or False).
  • iterable → The sequence to filter (list, tuple, etc.).

Example 1: Lambda with filter() (Single Iterable)
Let us see an example to filter even numbers:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))

print(evens) 

Output

[2, 4, 6, 8]

In the above code,

  • We start with a list of numbers: [1,2,3,4,5,6,7,8,9].
  • The lambda x: x % 2 == 0 checks if each number is even.
  • filter() applies this check to every element in the list.
  • Only numbers returning True (even ones) are kept.
  • Wrapping with list() gives [2,4,6,8] as the final result.

Example 2: Lambda with filter() (Single Iterable)
Let us see an example to filter odd numbers:

# Lambda with Python Built-in function filter() (Single Iterable)
# Filter odd numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# filter(function, iterable)
res = filter(lambda x: x % 2 != 0, numbers)

print(list(res))

Output

[1, 3, 5, 7, 9]

Example 3: Lambda with filter() (Single Iterable)
Let us see an example to get numbers greater than 5:

# Lambda with Python Built-in function filter() (Single Iterable)
# Get numbers greater than 5

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

res = filter(lambda x: x > 5, numbers)

print(list(res))

Output

[6, 7, 8, 9]

Example 4: Lambda with filter() (Single Iterable)
Let us see an example to get even numbers from a Tuple:

# Lambda with Python Built-in function filter() (Single Iterable)
# Get even numbers from a Tuple

# Tuple
numbers = (1, 2, 3, 4, 5)

res = filter(lambda x: x% 2 == 0, numbers)

print(tuple(res))

Output

(2, 4)

map() vs filter() in Python

Since we discussed some examples of map() and filter() above, let us now see the major differences:

map() vs filter() in Python

Python Tutorial (English)

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More

Python File Handling
Python - Get User Input
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment