Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/test/lambda_.py
1396 views
1
# No args
2
nothing = lambda: None
3
4
assert nothing() == None
5
6
# simple functions
7
8
add = lambda a, b: a + b
9
sub = lambda a, b: a - b
10
11
assert add(1, 2) == 3
12
assert sub(1, 2) == -1
13
14
# kwargs with defaults
15
16
f = lambda a, b=7, c=10: a + b * c
17
assert f(1, 2, 3) == 1 + 2 * 3
18
assert f(1, c=20) == 1 + 7 * 20
19
assert f(1, b=10) == 1 + 10 * 10
20
assert f(0) == 7 * 10
21
22
# vargs
23
f = lambda *args: args
24
assert list(f(['hello'])) == [['hello']]
25
26
assert list(f('hello', 'world')) == ['hello', 'world']
27
28
# varkwds
29
30
f = lambda **kwds: kwds
31
assert f(a=10) == {'a': 10}
32
33
# both
34
35
f = lambda *args, **kwds: [args, kwds]
36
37
v = f('hello', world='there')
38
assert list(v[0]) == ['hello']
39
assert v[1] == {'world': 'there'}
40
41
# Examples from people arguing about Python and lambda on Hacker News today
42
#
43
44
v = list(filter(lambda x: x < 10, map(lambda x: x * x, [1, 2, 3, 4])))
45
assert v == [1, 4, 9]
46
47
assert v == [x * x for x in [1, 2, 3, 4] if x * x < 10]
48
49
50
n = (lambda x: x+1 if \
51
True \
52
else x+x)\
53
(10)
54
assert n == 11
55
56