Built-in Functions
We will explore more built-in functions that are especially useful when working with the functional programming concepts we’ve learned so far.
max() and min()
The max() and min() functions return the largest and smallest items in an iterable, respectively.
With key Parameter
The key parameter allows you to specify a function that determines how items are compared:
words = ["apple", "banana", "cherry", "date"]
# Find longest wordlongest = max(words, key=len)print(longest) # banana
# Find shortest wordshortest = min(words, key=len)print(shortest) # dateWith default Parameter
The default parameter specifies what to return if the iterable is empty:
empty_list = []
# Without default - raises ValueError# max(empty_list) # ValueError: max() arg is an empty sequence
# With defaultresult = max(empty_list, default=0)print(result) # 0
# Useful for finding maximum with fallbacknumbers = []max_value = max(numbers, default=None)print(max_value) # NoneFull Signature
max(iterable, *[, default=obj, key=func])min(iterable, *[, default=obj, key=func])Practical Examples
# Find student with highest scorestudents = [ {"name": "Alice", "score": 85}, {"name": "Bob", "score": 92}, {"name": "Charlie", "score": 78}]
top_student = max(students, key=lambda s: s["score"])print(top_student) # {'name': 'Bob', 'score': 92}
# Find point farthest from originpoints = [(1, 2), (3, 4), (0, 0), (5, 1)]farthest = max(points, key=lambda p: p[0]**2 + p[1]**2)print(farthest) # (5, 1)sorted()
The sorted() function returns a new sorted list from the items in an iterable.
Basic Usage
numbers = [3, 1, 4, 1, 5, 9, 2, 6]sorted_numbers = sorted(numbers)print(sorted_numbers) # [1, 1, 2, 3, 4, 5, 6, 9]print(numbers) # [3, 1, 4, 1, 5, 9, 2, 6] (original unchanged)With key Parameter
Sort by a specific criterion:
words = ["apple", "banana", "cherry", "date"]
# Sort by lengthsorted_by_length = sorted(words, key=len)print(sorted_by_length) # ['date', 'apple', 'banana', 'cherry']
# Sort by last lettersorted_by_last = sorted(words, key=lambda w: w[-1])print(sorted_by_last) # ['banana', 'apple', 'date', 'cherry']With reverse Parameter
Sort in descending order:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Ascending (default)ascending = sorted(numbers)print(ascending) # [1, 1, 2, 3, 4, 5, 6, 9]
# Descendingdescending = sorted(numbers, reverse=True)print(descending) # [9, 6, 5, 4, 3, 2, 1, 1]Full Signature
sorted(iterable, /, *, key=None, reverse=False)Note: The / indicates that all arguments before it are position-only, and * indicates that arguments after it are keyword-only.
Practical Examples
# Sort students by score (descending)students = [ {"name": "Alice", "score": 85}, {"name": "Bob", "score": 92}, {"name": "Charlie", "score": 78}]
sorted_students = sorted(students, key=lambda s: s["score"], reverse=True)for student in sorted_students: print(f"{student['name']}: {student['score']}")# Bob: 92# Alice: 85# Charlie: 78
# Sort by multiple criteriapeople = [ ("Alice", 25, "Engineer"), ("Bob", 30, "Designer"), ("Charlie", 25, "Engineer")]
# Sort by age, then by namesorted_people = sorted(people, key=lambda p: (p[1], p[0]))print(sorted_people)# [('Alice', 25, 'Engineer'), ('Charlie', 25, 'Engineer'), ('Bob', 30, 'Designer')]map()
The map() function applies a function to every item in an iterable and returns an iterator.
Basic Usage
numbers = [1, 2, 3, 4, 5]
# Square each numbersquared = map(lambda x: x ** 2, numbers)print(list(squared)) # [1, 4, 9, 16, 25]Note
map()returns an iterator, so you need to convert it to a list to see all results at once.
With Named Functions
def square(x): return x ** 2
numbers = [1, 2, 3, 4, 5]squared = map(square, numbers)print(list(squared)) # [1, 4, 9, 16, 25]With Multiple Iterables
map() can take multiple iterables:
numbers1 = [1, 2, 3]numbers2 = [4, 5, 6]
# Add corresponding elementssums = map(lambda x, y: x + y, numbers1, numbers2)print(list(sums)) # [5, 7, 9]Full Signature
map(func, *iterables)Practical Examples
# Convert strings to uppercasewords = ["hello", "world", "python"]uppercase = list(map(str.upper, words))print(uppercase) # ['HELLO', 'WORLD', 'PYTHON']
# Convert temperatures from Celsius to Fahrenheitcelsius = [0, 10, 20, 30, 40]fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))print(fahrenheit) # [32.0, 50.0, 68.0, 86.0, 104.0]
# Extract specific fields from dictionariesstudents = [ {"name": "Alice", "age": 20, "grade": "A"}, {"name": "Bob", "age": 21, "grade": "B"}, {"name": "Charlie", "age": 19, "grade": "A"}]names = list(map(lambda s: s["name"], students))print(names) # ['Alice', 'Bob', 'Charlie']filter()
The filter() function constructs an iterator from elements of an iterable for which a function returns True.
Basic Usage
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Filter even numbersevens = filter(lambda x: x % 2 == 0, numbers)print(list(evens)) # [2, 4, 6, 8, 10]With Named Functions
def is_even(x): return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]evens = filter(is_even, numbers)print(list(evens)) # [2, 4, 6, 8, 10]With None as Function
If the function is None, filter() removes all falsy values:
values = [0, 1, False, True, "", "hello", None, [], [1, 2]]truthy = filter(None, values)print(list(truthy)) # [1, True, 'hello', [1, 2]]Full Signature
filter(func, iterable)Practical Examples
# Filter positive numbersnumbers = [-5, -2, 0, 3, 7, -1, 4]positive = list(filter(lambda x: x > 0, numbers))print(positive) # [3, 7, 4]
# Filter words longer than 5 characterswords = ["apple", "banana", "cat", "dog", "elephant"]long_words = list(filter(lambda w: len(w) > 5, words))print(long_words) # ['banana', 'elephant']
# Filter students with passing gradesstudents = [ {"name": "Alice", "score": 85}, {"name": "Bob", "score": 45}, {"name": "Charlie", "score": 92}, {"name": "Diana", "score": 60}]passing = list(filter(lambda s: s["score"] >= 60, students))for student in passing: print(f"{student['name']}: {student['score']}")# Alice: 85# Charlie: 92# Diana: 60Combining Built-in Functions
You can chain these functions together for powerful data processing:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Square even numbers and find the maximumresult = max(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))print(result) # 100 (10 squared)
# Filter, transform, and sortwords = ["apple", "banana", "cherry", "date", "elderberry"]result = sorted( map(str.upper, filter(lambda w: len(w) > 5, words)), key=len, reverse=True)print(result) # ['ELDERBERRY', 'BANANA', 'CHERRY']Comparison with List Comprehensions
Many operations with map() and filter() can also be done with list comprehensions:
numbers = [1, 2, 3, 4, 5]
# Using mapsquared_map = list(map(lambda x: x ** 2, numbers))
# Using list comprehensionsquared_comp = [x ** 2 for x in numbers]
# Using filterevens_filter = list(filter(lambda x: x % 2 == 0, numbers))
# Using list comprehensionevens_comp = [x for x in numbers if x % 2 == 0]
# Both approaches work, choose based on readabilityNote
List comprehensions are often more readable for simple operations, while
map()andfilter()can be more efficient for very large datasets or when you need lazy evaluation.
These built-in functions are essential tools for working with data in Python, providing efficient and readable ways to process iterables.
Exercises
Exercise 1: max() and min()
Given a list of student scores: [85, 92, 78, 96, 88], use max() and min() to find the highest and lowest scores. Also find the student with the longest name from ["Alice", "Bob", "Charlie", "Diana"] using the key parameter.
scores = [85, 92, 78, 96, 88]print(max(scores)) # 96print(min(scores)) # 78
names = ["Alice", "Bob", "Charlie", "Diana"]longest = max(names, key=len)print(longest) # CharlieExercise 2: sorted()
Sort the list [3, 1, 4, 1, 5, 9, 2, 6] in descending order. Then sort the words ["apple", "banana", "cherry", "date"] by length (shortest first).
numbers = [3, 1, 4, 1, 5, 9, 2, 6]descending = sorted(numbers, reverse=True)print(descending) # [9, 6, 5, 4, 3, 2, 1, 1]
words = ["apple", "banana", "cherry", "date"]sorted_by_length = sorted(words, key=len)print(sorted_by_length) # ['date', 'apple', 'banana', 'cherry']Exercise 3: map()
Use map() to convert a list of temperatures in Celsius to Fahrenheit. The formula is F = (C * 9/5) + 32. Read the number of temperatures, then read each temperature.
Temperature Conversion with map()
n = int(input())celsius = []for i in range(n): celsius.append(int(input()))
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))print(fahrenheit)Exercise 4: filter()
Use filter() to get all even numbers from a list. Read the number of integers, then read each integer.
Filter Even Numbers
n = int(input())numbers = []for i in range(n): numbers.append(int(input()))
evens = list(filter(lambda x: x % 2 == 0, numbers))print(evens)Exercise 5: Combining Built-in Functions
Given a list of numbers [5, 2, 8, 1, 9, 3], use filter() to get numbers greater than 4, then use map() to square them, and finally use max() to find the maximum squared value.
numbers = [5, 2, 8, 1, 9, 3]filtered = filter(lambda x: x > 4, numbers)squared = map(lambda x: x ** 2, filtered)result = max(squared)print(result) # 81 (9 squared)