⚡0 XP🔥0

Lambda, map(), filter() and sorted(key=)

Lesson 22 of 33 ⏱ 4 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Write small anonymous functions with lambda and use them with map, filter, sorted, max/min and reduce.

Functions are objects#

In Python, functions are values like numbers and strings. You can store them in variables and pass them to other functions:

▶ Try it YourselfPython
Ctrl + Enter to run

A function that takes another function as an argument (like apply) is called a higher-order function. map, filter and sorted are built-in higher-order functions.

lambda - small anonymous functions#

lambda parameters: expression

A lambda is a one-line function without a name. It automatically returns the value of its expression.

▶ Try it YourselfPython
Ctrl + Enter to run

The two definitions below are equivalent:

def square(x):
    return x * x

square = lambda x: x * x
हिंदी में समझें

Lambda एक छोटा, बिना नाम का function है जो सिर्फ एक line में लिखा जाता है। इसमें return लिखने की ज़रूरत नहीं - expression का जवाब अपने आप return हो जाता है।

lambda x: x * x को ऐसे पढ़ें: "x लो, और x × x लौटा दो।"

Lambda का असली फायदा तब है जब किसी function (जैसे sorted, map, filter) को एक छोटा-सा "नियम" देना हो, और उसके लिए पूरा def लिखना ज़रूरत से ज़्यादा लगे।

Tip

Lambdas are for short, throw-away functions. If you're assigning a lambda to a name (like square = lambda ...), a regular def is usually clearer. Use lambda mainly inline, as an argument.

map() - transform every item#

map(function, iterable) applies the function to each item and gives back the results:

▶ Try it YourselfPython
Ctrl + Enter to run
Did you know?

map returns a lazy map object, not a list. Wrap it in list() to see the values, or loop over it directly. This is also why map(int, input().split()) works for reading numbers.

filter() - keep matching items#

filter(function, iterable) keeps only the items where the function returns True:

▶ Try it YourselfPython
Ctrl + Enter to run

sorted(), max(), min() with key=#

The key parameter takes a function that returns the value to compare:

▶ Try it YourselfPython
Ctrl + Enter to run

Sorting a list of dictionaries:

▶ Try it YourselfPython
Ctrl + Enter to run

reduce() - combine into one value#

reduce (from the functools module) repeatedly combines items into a single result:

▶ Try it YourselfPython
Ctrl + Enter to run

map/filter vs comprehensions#

The same results can often be written as list comprehensions (coming in a later lesson), which many Python developers find more readable:

squares = list(map(lambda n: n * n, nums))
squares = [n * n for n in nums]                 # comprehension

evens = list(filter(lambda n: n % 2 == 0, nums))
evens = [n for n in nums if n % 2 == 0]         # comprehension

Both styles are correct - you should be able to read both.

Summary#

  • Functions are objects; they can be passed to other functions.
  • lambda args: expression creates a small anonymous function.
  • map(f, items) transforms each item; filter(f, items) keeps items where f is True.
  • sorted, max, min accept key= to choose what to compare.
  • functools.reduce combines items into one value.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Squares with map

Use map and a lambda to create a list squares of the squares of nums, then print it.

Expected output:
[1, 4, 9, 16, 25]
2

Passed students with filter

Use filter to keep only the marks >= 40 from marks. Store the result as a list in passed and print it.

Expected output:
[72, 40, 90, 55]
3

Sort products by price

Sort products (a list of (name, price) tuples) by price, highest first, and print each as name - price.

Expected output:
Bag - 850
Lamp - 499
Book - 240
Pen - 20

Quick Quiz

Q1.

What is (lambda x: x * 3)(4)?

Q2.

What does list(map(str.upper, ["a", "b"])) give?

Q3.

What does list(filter(lambda n: n > 2, [1, 2, 3, 4])) give?

Q4.

How do you sort words by length?

Q5.

Which is true about lambda functions?