January 27, 2026 · All About CS
Python Lists — Part 3: Built-in Functions for Lists
Learn how Python's built-in functions — len(), sum(), min(), max(), sorted(), list(), enumerate(), and zip() — make working with lists cleaner and more Pythonic.
Python Lists — Part 3: Built-in Functions for Lists
In Parts 1 and 2, we covered list fundamentals and the methods attached to every list object. This final part shifts focus to Python's built-in functions — functions that live in the global namespace and accept lists (or any iterable) as arguments. These functions are essential to writing clean, expressive Python and are used in virtually every real-world program.
Measuring and Aggregating
len() — Get the Length
len() returns the number of elements in a list. It runs in O(1) time because Python tracks the count internally.
fruits = ["apple", "banana", "cherry", "date"]
print(len(fruits)) # 4
empty = []
print(len(empty)) # 0A common pattern is using len() to guard against empty lists:
scores = []
if len(scores) > 0:
average = sum(scores) / len(scores)
else:
average = 0In boolean contexts, an empty list is falsy. You can simplify the check above to if scores: instead of if len(scores) > 0: — both are idiomatic, but the shorter form is preferred.
sum() — Total Numeric Elements
sum() adds up all elements in an iterable. It accepts an optional start value (default 0).
prices = [19.99, 35.50, 12.00, 8.75]
total = sum(prices)
print(total) # 76.24
# With a start value (e.g., shipping cost)
total_with_shipping = sum(prices, 5.00)
print(total_with_shipping) # 81.24sum() works with integers and floats. For decimal precision in financial calculations, use the decimal module.
min() and max() — Find Extremes
min() and max() return the smallest and largest elements, respectively. They work on any comparable elements.
temps = [22.5, 18.0, 31.2, 25.7, 14.3]
print(min(temps)) # 14.3
print(max(temps)) # 31.2Both accept an optional key function for custom comparisons:
words = ["banana", "apple", "cherry", "date"]
shortest = min(words, key=len)
longest = max(words, key=len)
print(shortest) # "date"
print(longest) # "banana"With structured data:
students = [
{"name": "Alice", "gpa": 3.8},
{"name": "Bob", "gpa": 3.2},
{"name": "Carol", "gpa": 3.9},
]
top = max(students, key=lambda s: s["gpa"])
print(top["name"]) # "Carol"Calling min() or max() on an empty list raises a ValueError. Pass the default parameter to handle this gracefully: min([], default=0).
Sorting Without Mutation
sorted() — Return a New Sorted List
While the .sort() method modifies a list in place, the sorted() function returns a brand-new sorted list, leaving the original untouched.
original = [5, 2, 9, 1, 7]
ascending = sorted(original)
descending = sorted(original, reverse=True)
print(original) # [5, 2, 9, 1, 7] — unchanged
print(ascending) # [1, 2, 5, 7, 9]
print(descending) # [9, 7, 5, 2, 1]sorted() works on any iterable, not just lists:
print(sorted("python")) # ['h', 'n', 'o', 'p', 't', 'y']
print(sorted({3, 1, 4, 1, 5})) # [1, 3, 4, 5]The key parameter works identically to .sort():
files = ["report.pdf", "notes.txt", "image.png", "data.csv"]
by_extension = sorted(files, key=lambda f: f.split(".")[-1])
print(by_extension)
# ["data.csv", "report.pdf", "image.png", "notes.txt"]When to Use sorted() vs .sort()
sorted() | .sort() | |
|---|---|---|
| Returns | New sorted list | None |
| Original | Unchanged | Modified in place |
| Works on | Any iterable | Lists only |
| Memory | Allocates new list | In-place (no extra memory) |
Use sorted() when you need the original order preserved or are working with non-list iterables. Use .sort() when you want to sort a list in place and save memory.
Type Conversion with list()
The list() constructor converts any iterable into a list.
From Strings
chars = list("hello")
print(chars) # ["h", "e", "l", "l", "o"]From Tuples
coordinates = (10, 20, 30)
coord_list = list(coordinates)
print(coord_list) # [10, 20, 30]From Ranges
numbers = list(range(1, 6))
print(numbers) # [1, 2, 3, 4, 5]
evens = list(range(0, 20, 2))
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]From Dictionaries
config = {"host": "localhost", "port": 8080, "debug": True}
print(list(config)) # ["host", "port", "debug"] — keys
print(list(config.values())) # ["localhost", 8080, True]
print(list(config.items())) # [("host", "localhost"), ("port", 8080), ("debug", True)]From Sets
unique = {3, 1, 4, 1, 5, 9}
ordered = sorted(list(unique))
print(ordered) # [1, 3, 4, 5, 9]Iterating with enumerate()
enumerate() wraps an iterable and yields (index, element) pairs. This eliminates the need for manual counter variables.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherryYou can set a custom starting index:
for rank, fruit in enumerate(fruits, start=1):
print(f"#{rank} {fruit}")
# #1 apple
# #2 banana
# #3 cherryPractical Use — Finding Positions
scores = [85, 92, 78, 95, 88, 73, 91]
high_scorers = [
(i, score) for i, score in enumerate(scores)
if score >= 90
]
print(high_scorers) # [(1, 92), (3, 95), (6, 91)]Prefer enumerate() over range(len(my_list)). It is more readable, less error-prone, and considered idiomatic Python.
Combining Lists with zip()
zip() takes two or more iterables and pairs their elements positionally, producing tuples. It stops at the shortest iterable.
names = ["Alice", "Bob", "Carol"]
scores = [92, 85, 91]
paired = list(zip(names, scores))
print(paired)
# [("Alice", 92), ("Bob", 85), ("Carol", 91)]Iterating Over Parallel Lists
names = ["Alice", "Bob", "Carol"]
scores = [92, 85, 91]
grades = ["A", "B", "A"]
for name, score, grade in zip(names, scores, grades):
print(f"{name}: {score} ({grade})")
# Alice: 92 (A)
# Bob: 85 (B)
# Carol: 91 (A)Building Dictionaries from Two Lists
keys = ["name", "age", "city"]
values = ["Alice", 30, "Seattle"]
person = dict(zip(keys, values))
print(person) # {"name": "Alice", "age": 30, "city": "Seattle"}Unequal-Length Lists
zip() truncates to the shortest list. Use itertools.zip_longest to pad with a fill value instead:
from itertools import zip_longest
a = [1, 2, 3]
b = ["x", "y"]
print(list(zip(a, b))) # [(1, "x"), (2, "y")]
print(list(zip_longest(a, b, fillvalue="-")))
# [(1, "x"), (2, "y"), (3, "-")]Complete Built-in Functions Reference
| Function | Description | Returns |
|---|---|---|
len(lst) | Number of elements | int |
sum(lst) | Sum of numeric elements | int or float |
min(lst) | Smallest element | Element type |
max(lst) | Largest element | Element type |
sorted(lst) | New sorted list | list |
list(iter) | Convert iterable to list | list |
enumerate(lst) | Index-element pairs | enumerate object |
zip(a, b) | Positional pairing | zip object |
Putting It All Together
scores = [85, 92, 78, 95, 88, 73, 91]
names = ["Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace"]
ranked = sorted(
zip(names, scores),
key=lambda pair: pair[1],
reverse=True,
)
print("=== Leaderboard ===")
for rank, (name, score) in enumerate(ranked, start=1):
print(f" #{rank} {name}: {score}")
print(f"\nHighest: {max(scores)}")
print(f"Lowest: {min(scores)}")
print(f"Average: {sum(scores) / len(scores):.1f}")
print(f"Total students: {len(scores)}")=== Leaderboard ===
#1 Dave: 95
#2 Bob: 92
#3 Grace: 91
#4 Eve: 88
#5 Alice: 85
#6 Carol: 78
#7 Frank: 73
Highest: 95
Lowest: 73
Average: 86.0
Total students: 7What We Covered in This Series
Across three parts, we explored Python lists from the ground up:
- Part 1 — Introduction, Indexing, and Mutability: What lists are, how to create them, positive/negative indexing, nested lists, and in-place modification.
- Part 2 — Essential List Methods: Every method for adding, removing, searching, sorting, and copying list elements.
- Part 3 — Built-in Functions for Lists: The global functions that operate on lists — measuring, aggregating, sorting without mutation, type conversion, and powerful iteration with
enumerate()andzip().
Lists are foundational to almost every Python program. Master them, and you have a reliable tool for everything from quick scripts to large-scale applications.