lambda functions

P

Pierre

Hello,

I would like to know if it is possible to define a loop in a lambda
function....

How to manage the indents ? Example :
s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s
[index]-1


Thanks !
 
C

Chris Rebert

Hello,

I would like to know if it is possible to define a loop in a lambda
function....

Not possible. Lambdas can only contain a single expression. A loop is
a block statement.
Just use a named function instead. There's nothing that can be done
with a lambda that can't be done with a named function instead.

Cheers,
Chris
 
G

Gabriel Genellina

I would like to know if it is possible to define a loop in a lambda
function....

How to manage the indents ? Example :
s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s
[index]-1

You can't. lambda is just a way to define a short, inline, anonymous
function, and its body can only contain expressions, not statements.

Even if what you want were legal, giving a name to the resulting
expression kind of defeats the purpose of lambda - use a normal function
instead:

def s_minus_1(s):
"document usage here"
for index,item in enumerate(s):
s[index] -= 1
 
P

Paul Rubin

Pierre said:
s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s
[index]-1

What are you trying to do here anyway? That looks broken.
Maybe you want the list.insert method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,125
Latest member
VinayKumar Nevatia_
Top