pyodide: loading…

[concept]Functions & Apply

Lambda Functions

# theory

lambdas

A lambda is a small, anonymous function. Instead of using def:

def double(x):
    return x * 2

You can write:

double = lambda x: x * 2

syntax

lambda arguments: expression
  • No def keyword
  • No function name (anonymous)
  • Single expression (no statements)
  • Implicit return

examples

# One argument
square = lambda x: x ** 2
print(square(5))  # 25

# Multiple arguments
add = lambda a, b: a + b
print(add(3, 4))  # 7

# With conditional
grade = lambda score: "Pass" if score >= 70 else "Fail"
print(grade(85))  # "Pass"

with map() and filter()

numbers = [1, 2, 3, 4, 5]

# map: apply function to each element
doubled = list(map(lambda x: x * 2, numbers))
# [2, 4, 6, 8, 10]

# filter: keep elements where function returns True
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]

# examples [3]

# example 01 · lambda with map()

Transform each element in a list

1
2
3
4
5
6
7
8
9
10
🐍
Loading PythonSetting up pandas & numpy...
# example 02 · lambda with filter()

Keep only elements meeting a condition

1
2
3
4
5
6
7
8
9
🐍
Loading PythonSetting up pandas & numpy...
# example 03 · lambda for sorting

Custom sort keys with lambda

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
🐍
Loading PythonSetting up pandas & numpy...

# challenges [2]

# challenge 01/02todo
Use map() with a lambda to convert ['hello', 'world'] to uppercase. Print the result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
🐍
Loading PythonSetting up pandas & numpy...
# challenge 02/02todo
Use filter() with a lambda to keep only strings longer than 3 chars from ['hi', 'hello', 'bye', 'goodbye'].
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
🐍
Loading PythonSetting up pandas & numpy...

# project

# project-challenge

thread: Sales Performance Dashboard · reward: 50 xp

# brief

The dashboard needs a quick revenue calculation for each sale. Use a lambda function to calculate Quantity times UnitPrice for all sales records.

# task

Calculate Revenue with Lambda

# your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
🐍
Loading PythonSetting up pandas & numpy...