DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Difference Between High-Level and Low-Level Programming Languages
  • How To Use ChatGPT With Python
  • The Power of Visualization in Exploratory Data Analysis (EDA)
  • Docker and Kubernetes Transforming Modern Deployment

Trending

  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications
  • Docker and Kubernetes Transforming Modern Deployment
  • REST vs. Message Brokers: Choosing the Right Communication
  • Getting Started With Prometheus Workshop: Instrumenting Applications
  1. DZone
  2. Coding
  3. Languages
  4. The Basics of Python Lambdas

The Basics of Python Lambdas

Lambdas, it's actually just all about taking a simple function and turning it into a one-liner.

Mike Driscoll user avatar by
Mike Driscoll
·
Oct. 30, 15 · Tutorial
Like (5)
Save
Tweet
Share
5.73K Views

Join the DZone community and get the full member experience.

Join For Free

many programming languages have the concept of the lambda function. in python, the lambda is an anonymous function or unbound function. the syntax for them looks a bit odd, but it’s actually just taking a simple function and turning it into a one-liner. let’s look at a regular simple function to start off:

#----------------------------------------------------------------------
def doubler(number):
    return x*2

all this function does is take an integer and double it. technically, it will also double other things too since there’s no type checking but that is its intent now let’s turn it into a lambda function!

fortunately, turning a one-line function into a lambda is pretty straight-forward. here’s how:

doubler = lambda x: x*2

so the lambda works in much the same way as the function. just so we’re clear, the “x” here is the argument you pass in. the colon delineates the argument list from the return value or expression. so when you get to the “x*2” part, that is what gets returned. let’s look at another example:

>>> poww = lambda i: i**2
>>> poww(2)
4
>>> poww(4)
16
>>> (lambda i: i**2)(6)
36

here we demonstrate how to create a lambda that takes an input and squares it. there’s some arguments in the python community about whether or not you should assign a lambda to a variable. the reason is that when you name a lambda, it’s no longer really anonymous and you might as well just write a regular function. the whole point of the lambda is to use it once and throw it away. the last example above shows one way to call a lambda anonymously (i.e. use it once).

besides, if you name the lambda, then you might as well just do this:

>>> def poww(i): return i**2
>>> poww(2)
4

let’s move on and see how to use a lambda in a list comprehension!

lambdas, list comprehensions and map

i’ve always had a hard time coming up with good uses for lambdas besides using them for event callbacks. so i went looking for some other use cases. it seems that some people like to use them in list comprehensions. here’s a couple of examples:

>>> [(lambda x: x*3)(i) for i in range(5)]
[0, 3, 6, 9, 12]
>>> tripler = lambda x: x*3
>>> [tripler(i) for i in range(5)]
[0, 3, 6, 9, 12]

the first example is a bit awkward. while it calls the lambda anonymously, it’s also a bit difficult to read. the next example assigns the lambda to a variable and then we call it that way. the funny thing about this is that python has a built-in way to call a function with an iterable called map . here’s how you would normally use it:

map(function, interable)

and here’s a real example using our lambda function from earlier:

>>> map(tripler, range(5))
[0, 3, 6, 9, 12]

of course, in most cases the lambda is so simple that doing the same thing inside the list comprehension is probably easier:

>>> [x*3 for x in range(5)]
[0, 3, 6, 9, 12]

other uses of lambda

my readers have suggested some other uses of lambda. the first example is returning a lambda from a function call:

>>> def increment(n): 
        return lambda(x): x + n
>>> i = increment(5)
>>> i(2)
7

here we create a function that will increment whatever we give to it by 5. one of my other readers suggested passing a lambda to python’s sorted function:

sorted(list, key=lambda i: i.address)

the idea here is to sort a list of objects with the property “address”. however, i still find the best use case for lambda is still for event callbacks, so let’s look at how to use them for that using tkinter.

using lambda for callbacks

lambda_tk

tkinter is a gui toolkit that comes built-in with python. when you want to interact with your user interface, you would normally use a keyboard and mouse. these interactions work via events, which is where the lambda makes its appearance. let’s create a simple user interface so you can see how lambda is used in tkinter!

import tkinter as tk

########################################################################
class app:
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """constructor"""
        frame = tk.frame(parent)
        frame.pack()

        print_btn = tk.button(frame, text='print',
                              command=lambda: self.onprint('print'))
        print_btn.pack(side=tk.left)

        close_btn = tk.button(frame, text='close', command=frame.quit)
        close_btn.pack(side=tk.left)

    #----------------------------------------------------------------------
    def onprint(self, num):
        print "you just printed something"

#----------------------------------------------------------------------
if __name__ == "__main__":
    root = tk.tk()
    app = app(root)
    root.mainloop()

so here we have a simple user interface with two buttons. one button calls the onprint method using a lambda while the other uses a tkinter method to close the application. as you can see, tkinter’s use of the lambda is as it was intended. the lambda here is used once and then thrown away. there is no way to reference it other than by pressing the button.

wrapping up

as my long time readers likely know, i wrote about the lambda in another article over five years ago. at that time, i didn’t have much use for lambdas and frankly i still don’t. they’re a neat feature of the language, but after programming in python for over 9 years, i’ve hardly ever found the need to use them, especially in the way that they are meant to be used. but to each their own. there’s certainly nothing wrong with using lambdas, but i hope you’ll find this article useful for figuring out whether or not you really do need to use them in your own work.

Python (language)

Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Difference Between High-Level and Low-Level Programming Languages
  • How To Use ChatGPT With Python
  • The Power of Visualization in Exploratory Data Analysis (EDA)
  • Docker and Kubernetes Transforming Modern Deployment

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: