DEV Community

kaelscion
kaelscion

Posted on • Updated on

Py in 5: Lambda Functions

py in 5 lambdas

originally published on the Coding Duck blog: www.ccstechme.com/coding-duck-blog

Today’s topic? Lambda functions! To start, let’s review the official definition of what the Python core team says a Lambda function is (otherwise called a Lambda expression). Per the docs:

Lambda expressions (sometimes called lambda forms) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression lambda parameters: expression yields a function object

Super clear right? No? Your not alone in thinking so. For many programmers Lambdas are features they know how to use, but don’t really understand what it is they are actually doing. The truth of the matter is that a Lambda function works like a regular function, it’s just shorter and more temporary. Like absurdly temporary. The phrases “single use” and “throw away” come to mind immediately. Let’s take a look at an example. Below is a traditional function that takes a number and cubes it (to the power of 3 or num*num*num):


def num_cubed(num):
  return num**3

Enter fullscreen mode Exit fullscreen mode

Neat. A function like this is not all that useful on it’s own and really only finds its stride when it is used repeatedly on a dataset like a list full of numbers that we wanted to cube. Using the function above we can go about this a couple of ways.

The cumbersome but highly readable way:


list_normal = [2, 4, 16, 10, 13, 7]
list_cubed = []
for num in list_normal:
  list_cubed.append(num_cubed(num))

Enter fullscreen mode Exit fullscreen mode

aaaaand the, very pythonic, one-liner by means of a list comprehension:


list_normal = [2, 4, 16, 10, 13, 7]
list_cubed = [num_cubed(x) for x in list_normal]

Enter fullscreen mode Exit fullscreen mode

So now we have a list of numbers and a list of cubed numbers. What does that have to do with lambdas? Can they do fun list things too? Yes, they can, as can be seen here:


list_normal = [2, 4, 16, 10, 13, 7]
list_cubed = list(map(lambda x: x**3, list_normal))

Enter fullscreen mode Exit fullscreen mode

But the use of list comprehensions does tend to be faster as the datasets get larger so they are preferred for this exact application. So what good are lambdas and what do they actually do???

Well, the best strength (and weakness) of lambda functions comes in situations where you only need to perform a specific task in a couple places in your code, while a normal function is best used when its functionality will be required over and over again within the same code file, or in different files.

Think of it this way: Let’s say your a carpenter building a house, but like a really weird house where nails just randomly come out of the wood sometimes as if they had never been nailed in. On most occasions, you would walk around the job site, looking for nails that came out. When you saw one, you’d take your trusty hammer from your belt, right where it always is, and hammer the nail back in 5 strikes of the hammer. That is using a normal function.

A lambda would be if you were walking around the house and saw 50 nails right in a row that had come out. You could hammer them all in with your 5 strike hammer. But there is also a hammer in the trailer that will do each nail in 2 strikes. Problem is, the trailer is 100 yards away and seeing as this is a super special hammer, it must always be kept in the trailer when not in use.

That make more sense? An ordinary function, when initialized, gets put into a spot where the Python interpreter can keep it close at hand. A lambda however, gets created the moment it is needed and removed the moment it is done. So, while it has the advantage of being able to do 10 lines of code worth of stuff in 20 characters or so, to have to “go get it from the trailer” for any reason but a special use case where it will be necessary to do the same task quickly then be done for the day doesn’t make much sense. In the long run, the lines of code you save are not nearly enough to justify the time it will take to “walk to the trailer” every time you see a loose nail. For that, just use your trusty old “belt hammer” in a regular function.

So I hope this clarifies lambda functions for you! If you have any questions, please leave a comment so that I can provide a bit more clarity on things I may have glazed over (I do only have 5 minutes as it is). As always, get out there and build, build, build! Never think that you cannot learn how to take a text editor and a bit of time and change the world. With all of the crap out there making the world miserable, and all of the technology built simply to help enough people waste enough time to make the developers rich, the world needs you and anybody else who desires to better themselves and the world by typing these funny phrases into a command line.

Top comments (5)

Collapse
 
thebouv profile image
Anthony Bouvier

Nice article. Minor typo:

list_cubed.append(num_cubed(num) is missing a ending paren in second code example.

Collapse
 
kaelscion profile image
kaelscion

thank you so much! I noticed that and the fact that I wrote "for x in list" a lot rather than "in list_normal". The typo you noticed and the one I just mentioned have been updated. Thank you so much for catching it!

Collapse
 
thebouv profile image
Anthony Bouvier

Awesome! Was just about to edit to point out the list/list_normal thing too.

Collapse
 
polimacs profile image
Stanislav Polimac

Dude, very neat explanation of lambdas and totally awesome ending of an article!!! I salute you for those closing lines!

Collapse
 
kaelscion profile image
kaelscion

Thanks so much!