Built-in Functions

Learn about essential built-in functions including max, min, sorted, map, and filter.

Ali Berro

By Ali Berro

9 min read Section 7
From: Python Fundamentals: From Zero to Hero

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:

max-min-key.py
words = ["apple", "banana", "cherry", "date"]
# Find longest word
longest = max(words, key=len)
print(longest) # banana
# Find shortest word
shortest = min(words, key=len)
print(shortest) # date

With default Parameter

The default parameter specifies what to return if the iterable is empty:

max-min-default.py
empty_list = []
# Without default - raises ValueError
# max(empty_list) # ValueError: max() arg is an empty sequence
# With default
result = max(empty_list, default=0)
print(result) # 0
# Useful for finding maximum with fallback
numbers = []
max_value = max(numbers, default=None)
print(max_value) # None

Full Signature

max(iterable, *[, default=obj, key=func])
min(iterable, *[, default=obj, key=func])

Practical Examples

max-min-examples.py
# Find student with highest score
students = [
{"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 origin
points = [(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

sorted-basic.py
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:

sorted-key.py
words = ["apple", "banana", "cherry", "date"]
# Sort by length
sorted_by_length = sorted(words, key=len)
print(sorted_by_length) # ['date', 'apple', 'banana', 'cherry']
# Sort by last letter
sorted_by_last = sorted(words, key=lambda w: w[-1])
print(sorted_by_last) # ['banana', 'apple', 'date', 'cherry']

With reverse Parameter

Sort in descending order:

sorted-reverse.py
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Ascending (default)
ascending = sorted(numbers)
print(ascending) # [1, 1, 2, 3, 4, 5, 6, 9]
# Descending
descending = 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

sorted-examples.py
# 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 criteria
people = [
("Alice", 25, "Engineer"),
("Bob", 30, "Designer"),
("Charlie", 25, "Engineer")
]
# Sort by age, then by name
sorted_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

map-basic.py
numbers = [1, 2, 3, 4, 5]
# Square each number
squared = 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

map-named-function.py
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:

map-multiple.py
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
# Add corresponding elements
sums = map(lambda x, y: x + y, numbers1, numbers2)
print(list(sums)) # [5, 7, 9]

Full Signature

map(func, *iterables)

Practical Examples

map-examples.py
# Convert strings to uppercase
words = ["hello", "world", "python"]
uppercase = list(map(str.upper, words))
print(uppercase) # ['HELLO', 'WORLD', 'PYTHON']
# Convert temperatures from Celsius to Fahrenheit
celsius = [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 dictionaries
students = [
{"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

filter-basic.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Filter even numbers
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # [2, 4, 6, 8, 10]

With Named Functions

filter-named-function.py
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:

filter-none.py
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-examples.py
# Filter positive numbers
numbers = [-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 characters
words = ["apple", "banana", "cat", "dog", "elephant"]
long_words = list(filter(lambda w: len(w) > 5, words))
print(long_words) # ['banana', 'elephant']
# Filter students with passing grades
students = [
{"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: 60

Combining Built-in Functions

You can chain these functions together for powerful data processing:

combining-functions.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Square even numbers and find the maximum
result = max(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))
print(result) # 100 (10 squared)
# Filter, transform, and sort
words = ["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:

comprehension-comparison.py
numbers = [1, 2, 3, 4, 5]
# Using map
squared_map = list(map(lambda x: x ** 2, numbers))
# Using list comprehension
squared_comp = [x ** 2 for x in numbers]
# Using filter
evens_filter = list(filter(lambda x: x % 2 == 0, numbers))
# Using list comprehension
evens_comp = [x for x in numbers if x % 2 == 0]
# Both approaches work, choose based on readability

Note

List comprehensions are often more readable for simple operations, while map() and filter() 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.

Answer:
scores = [85, 92, 78, 96, 88]
print(max(scores)) # 96
print(min(scores)) # 78
names = ["Alice", "Bob", "Charlie", "Diana"]
longest = max(names, key=len)
print(longest) # Charlie

Exercise 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).

Answer:
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()

Checks: 0 times
Answer:
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

Checks: 0 times
Answer:
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.

Answer:
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)

Course Progress

Section 37 of 61

Back to Course