CoCalc -- Collaborative Calculation in the Cloud
Sharedsage_worksheets / lambda_functions.ipynbOpen in CoCalc

Worksheets related to Applied Discrete Structures

Lambda functions

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.

f=lambda x:[x,x^2]
f
<function <lambda> at 0x7f7d8f6a60c8>
f(5)
[5, 25]
var('a')
f(a^2+1)
[a^2 + 1, (a^2 + 1)^2]
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.

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)]
list_plot(pairs)
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]
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]
import random
data=[randint(1,1000) for i in range(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.

data.sort()
data
[1, 522, 527, 555, 623, 641, 717, 741, 791, 899]
data.sort(key=lambda k:-(k%10))
data
[899, 527, 717, 555, 623, 522, 1, 641, 741, 791]