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.

pythonlistsbuilt-in-functionsdata-structuresbeginner
Python ListsPart 3 of 3

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.

Python
fruits = ["apple", "banana", "cherry", "date"]
print(len(fruits))  # 4

empty = []
print(len(empty))   # 0

A common pattern is using len() to guard against empty lists:

Python
scores = []
if len(scores) > 0:
    average = sum(scores) / len(scores)
else:
    average = 0

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

Python
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.24

sum() 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.

Python
temps = [22.5, 18.0, 31.2, 25.7, 14.3]

print(min(temps))  # 14.3
print(max(temps))  # 31.2

Both accept an optional key function for custom comparisons:

Python
words = ["banana", "apple", "cherry", "date"]

shortest = min(words, key=len)
longest  = max(words, key=len)

print(shortest)  # "date"
print(longest)   # "banana"

With structured data:

Python
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.

Python
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:

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

Python
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()
ReturnsNew sorted listNone
OriginalUnchangedModified in place
Works onAny iterableLists only
MemoryAllocates new listIn-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

Python
chars = list("hello")
print(chars)  # ["h", "e", "l", "l", "o"]

From Tuples

Python
coordinates = (10, 20, 30)
coord_list = list(coordinates)
print(coord_list)  # [10, 20, 30]

From Ranges

Python
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

Python
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

Python
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.

Python
fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

You can set a custom starting index:

Python
for rank, fruit in enumerate(fruits, start=1):
    print(f"#{rank} {fruit}")
# #1 apple
# #2 banana
# #3 cherry

Practical Use — Finding Positions

Python
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.

Python
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

Python
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

Python
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:

Python
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

FunctionDescriptionReturns
len(lst)Number of elementsint
sum(lst)Sum of numeric elementsint or float
min(lst)Smallest elementElement type
max(lst)Largest elementElement type
sorted(lst)New sorted listlist
list(iter)Convert iterable to listlist
enumerate(lst)Index-element pairsenumerate object
zip(a, b)Positional pairingzip object

Putting It All Together

Python
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: 7

What 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() and zip().

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.

Python ListsPart 3 of 3