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
Some other articles
Y111 - More on Collections and Sequences Mutable v Immuatble objects in Python, and the implication Accessing variables across subroutine boundaries - Perl, Python, Java and Tcl zip in Python Python for loops - applying a temporary second name to the same object List slices in Python - 2 and 3 values forms, with an uplifting example Python dictionaries - mutable and immutable keys and values Copying - duplicating data, or just adding a name? Perl and Python compared Sorting - naturally, or into a different order Sorting people by their names Python - access to variables in the outer scope List Comprehensions in Python This article Callbacks - a more complex code sandwich Last elements in a Perl or Python list Python - extend v append on a list Copying a reference, or cloning What is a callback? Python is a fabulous language Y105 - Functions, Modules and Packages From and Import in Python - where is the module loaded from? Embedding more complex code into a named block Nesting decorators Recursion in Python - the classic example What are callbacks? Why use them? An example in Python What is the difference between a function and a method? Reading command line parameters in Python A good example of recursion - a real use in Python Python - even named code blocks are objects Multiple yields and no loops in a Python generator? Python functions - an introduction to how they work Python varables - checking existance, and call by name or by value? Exception, Lambda, Generator, Slice, Dict - examples in one Python program vargs in Python - how to call a method with unknown number of parameters Optional positional and named parameters in Python Default local - a good choice by the author of Python Static variables in Python? Python timing - when to use a list, and when to use a generator Functions are first class variables in Lua and Python Finding all the unique lines in a file, using Python or Perl Python Packages - groupings of modules. An introduction Static variables in functions - and better ways using objects Passing optional and named parameters to python methods Catching the fishes first? Passing parameters to Python functions - the options you have Returning multiple values from a function call in various languages - a comparison Using an exception to initialise a static variable in a Python function / method Python - some common questions answered in code examples Passing a variable number of parameters in to a function / method Program for reliability and efficiency - do not duplicate, but rather share and re-use Optional and named parameters to Python functions/methods Python - access to variables in the outer scope Global and Enable - two misused words! Good example of recursion in Python - analyse an RSS feed Sample code with errors in it on our web site Optional parameters to Python functions Multiple returns from a function in Python Conversion of OSI grid references to Eastings and Northings Dynamic code - Python Optional and named parameters in Python What to do with a huge crop of apples This article Sharing variables with functions, but keeping them local too - Python Global - Tcl, PHP, Python Python Script - easy examples of lots of basics Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code Function / method parameters with * and ** in Python It's the 1st, not the 1nd 1rd or 1th. Sludge off the mountain, and Python and PHP Python - A list of methods Recursion in Python Python - function v method Dynamic functions and names - Python Do not duplicate your code Cottage industry or production line data handling methods Python modules. The distribution, The Cheese Shop and the Vaults of Parnassus. Python - block insets help with documentation Python's Generator functions Difference between import and from in Python What is a callback? Code and code maintainance efficiency Call by name v call by value Lambdas in Python Python generator functions, lambdas, and iterators Distance Learning Variable Scope