Collection Built-ins

Built-in Functions

Collection Built-ins

In this tutorial, we'll use len(), sorted(), sum(), min(), max(), and enumerate().

Python has built-in functions that work well with lists, tuples, sets, dictionaries, and strings.

len()

len() counts items:

names = ["Ada", "Grace", "Linus"]
print(len(names))
print(len("Python"))

sum()

sum() adds numbers:

scores = [8, 10, 7]
print(sum(scores))

This is shorter than writing a loop when all you need is the total.

min() and max()

scores = [8, 10, 7]

print(min(scores))
print(max(scores))

These find the smallest and largest values.

sorted()

sorted() returns a sorted list:

names = ["Linus", "Ada", "Grace"]
sorted_names = sorted(names)

print(sorted_names)
print(names)

The original list is not changed.

enumerate()

enumerate() gives you an index and item while looping:

names = ["Ada", "Grace", "Linus"]

for index, name in enumerate(names):
    print(index, name)

This is cleaner than manually updating a counter.

sorted() vs list.sort()

sorted() gives you a new sorted list. The original stays the same.

names = ["Linus", "Ada", "Grace"]
print(sorted(names))
print(names)

Lists also have a .sort() method, but that changes the original list. As a beginner, sorted() is often easier to reason about.

Practice

Create a list of scores. Print the count, total, highest score, lowest score, and sorted scores.