Main Content

Python - A list of methods

Archive - Originally posted on "The Horse's Mouth" - 2006-11-03 06:52:30 - Graham Ellis

In Python everything - even named blocks of code - are objects. Which means that you can have a list or a dictionary of functions, and you can pass named blocks of code in and out of other functions and methods

games = []

colls = [350, 120.5, 1, 400, 289, 400]
c2 = [4,3,4,5,4,7]

games.append(lambda x,y: x//15 + y)

teams = map(games[0],colls,c2)
print teams


The code above shows you (briefly) the mechanism. By setting up dictionaries or lists of code, you can selectively run algorithms based on an index or key - something I've seen used really nicely as an alternative implementation to a switch which Python (rightly in my view) lacks.