Main Content

Anonymous functions (lambdas) and map in Python

Archive - Originally posted on "The Horse's Mouth" - 2008-11-04 18:32:19 - Graham Ellis

Why do you name variables? So that you can use them again later. But if you don't want to use them more than once, why bother with a name at all? Most programming languages create temporary or anonymous variables within a single line, and if you've programmed almost anything, you'll have used them without realising it.

In Python, everything is an object - and that includes functions. And so, just as you're allowed anonymous scalars and lists, you're allowed anonymous functions. They're defined using the lambda keyword ....

Here are some function definitions ....

def cricket(input):
  return input/11
 
rugby = lambda x: (x-7)/15
 
games = (cricket,
  rugby,
  lambda input:input/2,
  lambda x:x)
 
# and some data for the rest of the example
people = [150,175,210,50]


Let's now see some examples of how these functions are called, via the map function:

teams = map(cricket, people)
print "cricket - ",teams
 
teams = map(rugby, people)
print "rugby - ",teams
 
# Call a new (anonymous) function
teams = map(lambda x: x/7, people)
print "water polo - ",teams
 
# Loop through and call a list of functions
for k in range(0,len(games)):
  teams = map(games[k], people)
  print "seasonal - ",teams


Here are the results of running that code:

earth-wind-and-fire:~/nov08 grahamellis$ python mutton
cricket - [13, 15, 19, 4]
rugby - [9, 11, 13, 2]
water polo - [21, 25, 30, 7]
seasonal - [13, 15, 19, 4]
seasonal - [9, 11, 13, 2]
seasonal - [75, 87, 105, 25]
seasonal - [150, 175, 210, 50]
earth-wind-and-fire:~/nov08 grahamellis$


Full source code here ... learn more about this on our Python course