+3

Is it possible to do this with a lambda expression?

Let's say a have this function. def test(my_list): my_list.append(2) return my_list print(test([0, 1])) # [0, 1, 2] My question: Is it possible to do it with a lambda expression? This seems to work: f = lambda my_list: [my_list.append(2)]+[print(my_list)] f([0,1]) # [0, 1, 2] But I want the value to be returned (so I can use it later in the program) instead of being printed. Any thoughts?

2/9/2019 3:40:06 AM

Diego

4 Answers

New Answer

+6

s2 = [] u = lambda n: 0 if n in s2 else (s2.append(n) or 1+sum(u(j) for j in range(n-1,0,-1))) print(u(10)) #10 print(s2) #[10, 9, ..., 2, 1]

+4

appnd = lambda l: l + [2] print(appnd([0, 1])) # [0, 1, 2] This is probably too easy... Do you want to change the original list in place while returning the modified list? 🤔

+1

Anna Interesting... I tried using "and", but it never crossed my mind to use "or". Thanks!

0

Anna If I have this function: def test1(n): return 1+sum(test1(j) for j in range(n-1,0,-1)) I can turn it into this: f = lambda n: 1+sum(f(j) for j in range(n-1,0,-1)) print(test1(10)) # 512 print(f(10)) # 512 But how can I write this: s=[] def test2(n): if n in s: return 0 s.append(n) return 1+sum(test2(j) for j in range(n-1,0,-1)) print(test2(10)) # 10 Using a lambda expression?