Back to Blog

Lambda Functions (map, filter, sorted, anonymous functions) - Python Tutorial for Beginners #13

Sandy LaneSandy Lane

Video: Lambda Functions (map, filter, sorted, anonymous functions) - Python Tutorial for Beginners #13 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Lambda Functions (map, filter, sorted, anonymous functions) - Python Tutorial for Beginners #13

Lambda functions in Python provide a concise way to write small anonymous functions using the syntax lambda arguments: expression. This tutorial covers how to use lambdas with built-in functions like map(), filter(), and sorted() to write clean, functional-style code. You'll also see how to chain transformations and apply lambdas in practical scenarios like processing grades.

Code

# Basic lambda function with one argument
square = lambda x: x * x
print(square(5))  # Output: 25

# Lambda with multiple arguments
add = lambda x, y: x + y
print(add(3, 7))  # Output: 10

# Using lambda with map() to square each number in a list
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x * x, numbers))
print(squared)  # Output: [1, 4, 9, 16, 25]

# Using lambda with filter() to keep even numbers only
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # Output: [2, 4]

# Using lambda with sorted() and key parameter to sort by last letter
words = ['banana', 'apple', 'cherry', 'date']
sorted_words = sorted(words, key=lambda w: w[-1])
print(sorted_words)  # Output: ['banana', 'apple', 'date', 'cherry']

# Chaining map and filter: square even numbers only
even_squares = list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, numbers)))
print(even_squares)  # Output: [4, 16]

# Mini project: Grade processor using lambda
grades = [88, 92, 79, 93, 85]

# Convert numeric grades to letter grades
letter_grades = list(map(lambda g: 'A' if g >= 90 else 'B' if g >= 80 else 'C', grades))
print(letter_grades)  # Output: ['B', 'A', 'C', 'A', 'B']

Key Points

  • Lambda functions are anonymous, inline functions defined with the syntax lambda arguments: expression.
  • map() applies a lambda to every item in an iterable, returning a new iterable of results.
  • filter() uses a lambda to select items where the lambda returns True, filtering the iterable.
  • sorted() accepts a lambda as a key function to customize sorting criteria.
  • Lambdas can be combined and chained with built-ins to write concise and readable data transformations.