Python functions within lists
Solution 1
You can create anonymous functions using the lambda
keyword.
def func(x,keyword='bar'):
return (x,keyword)
is roughly equivalent to:
func = lambda x,keyword='bar':(x,keyword)
So, if you want to create a list with functions in it:
my_list = [lambda x:x**2,lambda x:x**3]
print my_list[0](2) #4
print my_list[1](2) #8
Solution 2
Not really in Python. As mgilson shows, you can do this with trivial functions, but they can only contain expressions, not statements, so are very limited (you can't assign to a variable, for example).
This is of course supported in other languages: in Javascript, for example, creating substantial anonymous functions and passing them around is a very idiomatic thing to do.
Solution 3
You can create the functions in the original scope, assign them to the array and then delete them from their original scope. Thus, you can indeed call them from the array but not as a local variable. I am not sure if this meets your requirements.
#! /usr/bin/python3.2
def a (x): print (x * 2)
def b (x): print (x ** 2)
l = [a, b]
del a
del b
l [0] (3) #works
l [1] (3) #works
a (3) #fails epicly
Solution 4
You can create a list of lambda
functions to increment by every number from 0 to 9 like so:
increment = [(lambda arg: (lambda x: arg + x))(i) for i in range(10)]
increment[0](1) #returns 1
increment[9](10) #returns 19
Side Note:
I think it's also important to note that this (function pointers not lambdas) is somewhat like how python holds methods in most classes, except instead of a list, it's a dictionary with function names pointing to the functions. In many but not all cases instance.func(args)
is equivalent to instance.__dict__['func'](args)
or type(class).__dict__['func'](args)
![Hovestar](https://i.stack.imgur.com/gsZzC.png?s=256&g=1)
Hovestar
I am currently a student at CU-Boulder studying CS and applied Math. My goal is to someday write a program that can derive mathmatics.
Updated on October 16, 2020Comments
-
Hovestar over 3 years
So today in computer science I asked about using a function as a variable. For example, I can create a function, such as
returnMe(i)
and make an array that will be used to call it. Likeh = [help,returnMe]
and then I can say h1 and it would callreturnMe("Bob")
. Sorry I was a little excited about this. My question is is there a way of calling likeh.append(def function)
and define a function that only exists in the array?EDIT:
Here Is some code that I wrote with this! So I just finished an awesome FizzBuzz with this solution thank you so much again! Here's that code as an example:
funct = [] s = "" def newFunct(str, num): return (lambda x: str if(x%num==0) else "") funct.append(newFunct("Fizz",3)) funct.append(newFunct("Buzz",5)) for x in range(1,101): for oper in funct: s += oper(x) s += ":"+str(x)+"\n" print s
-
Hovestar over 11 yearsSo This is so awesome! Thanks so much! We were also talking about fizzBuzz and I thought this would be so cool to solve it!
-
jsbueno over 11 yearsJust completing: This stands one of the distinctive things of Python and Javascript (among other languages that allow a functional approach). It is a design choice - that trades some flexibility for readability.
-
Hyperboreus over 11 yearsA side note. Lambda terms are not necessarily "trivial". The fact that they cannot contain statements does not limit them very much, if it does limit them at all (much of the statements are superfluous using a pure functional approach). The fact that you cannot assign to variables inside a lambda term, does not limit it at all. If these aspects were truly limitations, pure functional languages would be very limited (which they aren't). I am not even sure if there exists a python program such that it cannot be written as a lambda term (if it wasn't for the fact that python doesn't do LCO).
-
Hovestar over 10 yearsI also agree with @Hyperboreus I've played around a lot with lambdas in python and even wrote a genetic algorithm that was only two lines, one to import random and the other was about 2000 chars long...
-
Hyperboreus over 10 years@Hovestar The first line of the program you describe seems to be superfluous. You can import things functionally with
__import__
. E.g.(lambda r: r.randint (0, 5) ) (__import__('random') )
.