Lambda functions are often used in `map`

, `filter`

, and `sort`

. They are analogous to Mathematica pure functions. A pure function such as `{#,#^2}&`

in Mathematica would be the lambda function `lambda k:[k,k^2]`

in Python/SageMath.

In [1]:

f=lambda x:[x,x^2]

In [2]:

f

<function <lambda> at 0x7f7d8f6a60c8>

In [3]:

f(5)

[5, 25]

In [4]:

var('a') f(a^2+1)

[a^2 + 1, (a^2 + 1)^2]

In [5]:

map(lambda x:[x,x^2],range(10))

[[0, 0],
[1, 1],
[2, 4],
[3, 9],
[4, 16],
[5, 25],
[6, 36],
[7, 49],
[8, 64],
[9, 81]]

The list `[a,b]`

and the tuple `(a,b)`

are different. However, either can be used in plotting.

In [6]:

pairs=map(lambda x:(x^2,x),range(10));pairs

[(0, 0),
(1, 1),
(4, 2),
(9, 3),
(16, 4),
(25, 5),
(36, 6),
(49, 7),
(64, 8),
(81, 9)]

In [7]:

list_plot(pairs)

In [8]:

P=Primes() filter(lambda k:k in P,[1..100])

[2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97]

In [29]:

filter(lambda k:k.is_prime(),srange(1,100))

[2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97]

In [9]:

import random data=[randint(1,1000) for i in range(10)]

In [10]:

data

[717, 623, 641, 741, 527, 791, 899, 1, 555, 522]

The following expression doesn't produce an output but does act on the list.

In [11]:

data.sort()

In [12]:

data

[1, 522, 527, 555, 623, 641, 717, 741, 791, 899]

In [16]:

data.sort(key=lambda k:-(k%10))

In [17]:

data

[899, 527, 717, 555, 623, 522, 1, 641, 741, 791]

In [ ]:

```
```