Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define function as list element

Tags:

python

>>> list=[None]
>>> def list[0](x,y):
  File "<stdin>", line 1
    def list[0](x,y):
             ^
SyntaxError: invalid syntax

How can I define a function as an element of a list?

like image 615
ThePiercingPrince Avatar asked Nov 28 '22 02:11

ThePiercingPrince


2 Answers

Python's def isn't flexible enough to handle generic lvalues such as list[0]. The language only allows you to use an identifier as function name. Here are the relevant parts of the grammar rule for the def-statement:

funcdef        ::=  "def" funcname "(" [parameter_list] ")" ":" suite
funcname       ::=  identifier

Instead, you can use a series of assignment and definition statements:

s = [None]

def f(x, y):
    return x + y

s[0] = f

As an alternative, you could also store a lambda expression directly in a list:

s = [lambda x,y : x+y]
like image 71
Raymond Hettinger Avatar answered Dec 09 '22 08:12

Raymond Hettinger


def f(whatever):
    do_stuff()

l[0] = f

The function definition syntax doesn't allow you to define a function directly into a data structure, but you can just create the function and then assign it wherever it needs to go.

like image 37
user2357112 supports Monica Avatar answered Dec 09 '22 08:12

user2357112 supports Monica