>>> 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?
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With