• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Python Lambda Function List Comprehension | Map, Filter, Reduce

Aniruddha Chaudhari/58644/10
CodePython

In an earlier post, we have seen, 5 simplest programming languages for beginners. For obvious, Python is one of those.

Lambda is one of the very useful and advanced topics from Python.

This tutorial is all about Python Lambda Function List Comprehension. I will also demonstrate the use of lambda function with map(), filter() and reduce().

At the end of this tutorial, you will understand every basic practical detail you should know to use the Lambda function in your Python code.

If you are preparing for a Job interview, there is a high probability you will find many Python interview questions from the Lambda function.

Let’s begin.

Table of Contents

  • What is Python Lambda Function?
    • How are Lambda Functions Different from Normal Function Conceptually?
    • Calling Lambda Function
  • Python Lambda Function List Comprehension
  • What is the major Use of the Lambda Function?
    • Map Example using Lambda Function:
    • Filter Example using Lambda Function:
  • Summary

What is Python Lambda Function?

In Python, the function which does not have a name or does not associate with any function name is called the Lambda function.

It uses keyword lambda. Here is the simple syntax for the lambda function

lambda : expression

Below is a simple example.

lambda x:x*2

Here ‘x’ is an argument and ‘x*2’ is an expression in a lambda function.

How are Lambda Functions Different from Normal Function Conceptually?

We already know about the Python function. Normal function in python is created using keyword def as written below.

def multiply(x):
    x= x*2
    return x

Differences and similarities between Lambda and Normal Functions

  • Lambda function can have multiple or any number of arguments as like normal function.
  • It should have only one expression.
  • It uses the implicit return statement. So many people call it a single expression function. The single expression is evaluated and returned.

Calling Lambda Function

So, How is it possible to call this Python lambda function without its name?

You can assign a lambda function to some function object. After that, you can make a call to lambda function as like normal function in python.

Here is a simple program.

multiply = lambda x:x*2

print(multiply(10))
#output: 20

In another way, you can make it work without a function name as well.

(lambda x:x*2)(10)

We can say, it is just like an inline function.
It will return output the same as 20.

Lambda Function with Single Arguments:

Write a program to double a number using the lambda function in Python.

 
# Simple Program that shows the 
# use of lambda functions 
# with single argument

twice = lambda x: x * 2 

print(twice(5)) 
# Output: 10

In the above program, we have assigned a lambda function object to multiply and then we are calling it as twice(10). It will give output as 20.

Lambda Function with Multiple Arguments:

Write a program to add two numbers using the lambda function in Python.

# Simple Program that shows the 
# use of lambda functions 
# with single argument

add = lambda x, y: x + y

print(add(5, 3))
#Output: 8

Python Lambda Function List Comprehension

Looking at the given example for Python Lambda Function list comprehension. It multiplies each element of the list by two.

numbers = [1,2,4,5,3]
double = [x*2 for x in numbers]
print(double)
#Output: [2, 4, 8, 10, 6]

You can do the same with python lambda function with map().

numbers = [1,2,4,5,3]
double = map(lambda x: x*2 , numbers)
print(double)
#Output: [2, 4, 8, 10, 6]

Observe above both list comprehension and lambda/map() program carefully. You can see, there is the only difference between the rearrangement of words and the removal of ‘in’ and ‘for.’

Now you have seen, normal function and lambda function work the same. Then…

What is the major Use of the Lambda Function?

Lambda function is useful when you need passing function object to other functional concepts such as filter(), map() and reduce(). These three functional concepts have in common. They take two arguments: function object and list.

Take an example of the map.

Map Example using Lambda Function:

Write a program that reads the sentence and gives the output as the length of each word in a sentence in the form of a list.

sentence = 'I am learning Python programming with CSEstack'
words = sentence.split()
print words
['I', 'learn', 'Python', 'programming', 'with', 'CSEstack']

lengths = map(lambda word: len(word), words)
print lengths
[1, 5, 6, 11, 4, 8]

Filter Example using Lambda Function:

Write a Python program that takes a list containing numbers and returns all the odd numbers in the form of a list.

# Simple Program that filters out
# only the odd items from
# a list using filter() and
# lambda functions

my_list = [1, 9, 2, 7, 17, 44, 343, 14]
new_list = list(filter(lambda x: (x%2 == 1) , my_list))

print(new_list)
# Output: [1, 9, 7, 17, 343]

Python Lambda function comes very handily to automate certain tasks with a single line of code. With the single Lambda function call I can clear the Python interpreter console. It’s one of the very useful tricks I used every time while working with Python.

Summary

Here is a quick summary. Keep it in mind.

  • Lambda function is a very powerful and quick concept in Python programming.
  • In general, we use Python lambda function when we need a nameless function for a short duration.
  • Mostly it is used to pass as a function object to other functional concepts such as map(), filter() and reduce().

You can also read the following articles to learn more about Python:

  • Difference between Mutable and Immutable in Python
  • Python How to Randomly Select Item from List in Python
  • Python How to Find Unique Elements from List in Python?

Many geeks find lambda function difficult, so I tried to keep it as simple as possible. I have explained Python lambda function list comprehension with map, filter, reduce examples. It makes understanding easy.

If you have any doubt, write in a comment. I will keep posting more such tutorials. Stay tuned to learn and grow.

Python Interview Questions eBook

Pythonpython list
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Shardul Silswal
    April 3, 2018 at 1:25 am

    nicely explained!

    • Reply
      Aniruddha Chaudhari
      April 3, 2018 at 8:38 am

      Thanks, Shardul!

  • Reply
    Shakti Das
    October 29, 2018 at 7:35 am

    This is really an interesting topic on the python advance operator and one line function.

    • Reply
      Aniruddha Chaudhari
      October 29, 2018 at 8:15 pm

      Indeed, it is interesting.

  • Reply
    Makrand
    May 27, 2019 at 1:33 pm

    Lambda function is one of the toughest topics in Python as I know. But, you have explained it in very simple manners, Sir. Thanks!

    • Reply
      Aniruddha Chaudhari
      May 27, 2019 at 8:01 pm

      You’re welcome! Thanks for your kind words.

  • Reply
    ASMITA
    May 27, 2019 at 6:46 pm

    Sir, can u please provide an example for reduce()?

    • Reply
      Aniruddha Chaudhari
      May 27, 2019 at 8:02 pm

      Sure, Asmita. I’m taking note of it.

  • Reply
    Jere
    December 10, 2019 at 5:20 am

    This is one of a series of great explanations. Good job.
    There is one minor update you should make though:
    The output of the first list comprehension example should be [2, 4, 8, 10, 6].

    • Reply
      Aniruddha Chaudhari
      December 10, 2019 at 11:04 am

      Thanks, Jere for the correction. Fixed. I hope you enjoy my other Python tutorials as well.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard