 Sharedsage_worksheets / lambda_functions.ipynbOpen in CoCalc
Author: Ken Levasseur
Description: 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.

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

In :
f

<function <lambda> at 0x7f7d8f6a60c8>
In :
f(5)

[5, 25]
In :
var('a')
f(a^2+1)

[a^2 + 1, (a^2 + 1)^2]
In :
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 :
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 :
list_plot(pairs) In :
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 :
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 :
import random
data=[randint(1,1000) for i in range(10)]

In :
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 :
data.sort()

In :
data

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

In :
data

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