Kalebu Jordan

Become a Pro Python Developer


In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression.

Such a function is capable of behaving similarly to a regular function declared using the Python’s def keyword

Syntax of Lambda Function

lambda arguments : expression

Example of usage (app.py)

square = lambda number : number**2

Making the same Function using def keyword (app1.py)

def square(number):
  return number**2

As we can see There is extra line on writing a function using def keyword compared to lambda

Example of Usage(app2.py)

#_________Lambda Function replace spaces in sentence with -
Split_and_Join = lambda sentence:'-'.join(sentence.split(' '))
new_sentence = Split_and_Join('lambda function in python')

Making the same Function using def keyword (app3.py)

def split_and_join(sentence):
    words =sentence.split(' ')
    joined_sentence = '-'.join(words)
    return joined_sentence
new_sentence = split_and_join('lambda function in python')

Thing to Note :

  • Lambda function is a single line function that can consists as many as argument but only one expression
  • Use Lambda when you need a function for a short period of time and doesn’t consists a lot of Instruction

2 thoughts on “How to use lambda function in Python

Leave a Reply


Enjoy this blog? Please spread the word :)

%d bloggers like this: