+91 81900 98289

Python Lambda

This Python Lambda lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A lambda is a one-expression function without a name. It fits a sort key or another short callback.

When the logic needs more than one line, write a def. A named function is easier to test and to read a week later.

Example 1: Start here

The minus sign sorts from high to low. lambda score: score would sort from low to high.

scores = [61, 82, 90] # a list; the values stay in this order scores.sort(key=lambda score: -score) # sort this list in place print(scores)

Example 2: A one-line function

lambda creates a small function with one expression and no name of its own.

double = lambda n: n * 2 # a one-line function print(double(6))

Example 3: Sort with a key

The key function tells sort which value to compare.

rows = [{"name": "Arun", "score": 74}, {"name": "Meera", "score": 82}] # a list; the values stay in this order rows.sort(key=lambda row: row["score"]) # sort this list in place print([row["name"] for row in rows]) # in is True when the value is found

Example 4: Prefer def when it grows

Use def as soon as the function needs more than one line or a clear name.

def double(n): # define the function; it runs when you call it return n * 2 # send this value back to the caller print(double(6))
The minus sign sorts from high to low. lambda score: score would sort from low to high.
Call Now 81900 98289