Python's Built-in Collection Functions

Learn Python's built-in functions that work across all collection types: len(), min(), max(), sum(), sorted(), reversed(), zip(), and enumerate().

5 min read

Python's built-in collection functions are a set of tools that operate on every collection type without you needing to import anything. These functions answer the most common questions you ask about a collection: how many items does it contain, what is the smallest or largest value, what is the sum of all numbers, and how can you sort or reverse the data without modifying the original. They are part of the core language, they are optimized in C, and they work the same way whether you pass them a list, a tuple, a set, or the keys or values of a dictionary.

If you have worked through the earlier articles in this section, you have already seen several of these functions in action. The len function appeared when checking list sizes and dictionary entry counts. The sorted function appeared in articles on sorting and reversing Python lists and in the discussion of iterating over sets in a predictable order. This article brings all the cross-collection built-ins together so you can see the full toolkit in one place and understand when to use each function.

Counting and measuring with len

The len function returns the number of items in a collection. It works on every built-in collection type and runs in constant time because Python tracks the size of each collection internally. For a list or tuple, len returns the count of elements. For a set, it returns the count of unique elements. For a dictionary, it returns the count of key-value pairs.

The len function does not count nested items. If you have a list of lists, len returns the number of inner lists, not the total number of elements across all inner lists. To count everything in a nested structure, you need to iterate and sum the lengths of each inner collection, or flatten the structure first.

Finding extremes with min and max

The min and max functions find the smallest and largest elements in a collection, respectively. They work on any iterable whose elements can be compared with the less-than and greater-than operators. Numbers, strings, and tuples of comparable elements all work. Mixed types that cannot be compared, like integers and strings in the same list, will raise a TypeError.

pythonpython
scores = [85, 92, 78, 95, 88]
lowest = min(scores)
highest = max(scores)

For strings, comparison uses Unicode code point order, which means uppercase letters sort before lowercase letters. The words "Apple" and "banana" would order with "Apple" first because uppercase A has a lower code point than lowercase b. For case-insensitive minimum and maximum, use the key parameter, which works the same way as the key parameter on sorted and sort.

When called on a dictionary, min and max operate on the keys, not the values. To find the smallest or largest value, pass the dictionary's values view explicitly. To find the key associated with the smallest or largest value, pass the items view with a key function that extracts the value from each pair.

Summing numeric collections with sum

The sum function adds up all the numeric values in an iterable and returns the total. It accepts an optional second argument that serves as the starting value, which defaults to zero. Use the start argument when you are summing non-integer types like floats or Decimal objects and want the result type to match.

pythonpython
expenses = [45.50, 32.00, 78.25, 15.90]
total = sum(expenses)

The sum function is optimized for numeric addition and should not be used to concatenate strings. String concatenation in a loop creates many intermediate string objects, which is inefficient. Use the join method on an empty string instead, which precomputes the total length and allocates the result in one pass. The sum function is similarly not appropriate for combining lists; use a list comprehension or the extend method in a loop instead.

Sorting and reversing with sorted and reversed

The sorted function accepts any iterable and returns a new list with the items in ascending order. It accepts the same key and reverse parameters as the list sort method, making it the universal sorting tool for all collection types. Pass a set to sorted to get a predictable, ordered list of unique items. Pass the items of a dictionary to sort by key or by value using a key function.

The reversed function accepts any sequence and returns an iterator that yields items in reverse order. It does not create a new list; it produces items one at a time as you iterate. To get a reversed list, pass the result to the list constructor. For dictionaries, reversed iterates over the keys in reverse insertion order, which is available since Python 3.8.

Pairing with zip and enumerate

The zip function takes multiple iterables and returns an iterator of tuples, where the first tuple contains the first element from each iterable, the second tuple contains the second element from each, and so on. Iteration stops when the shortest input iterable is exhausted. Zip is the standard way to walk through two or more parallel sequences in lockstep.

pythonpython
names = ["Alice", "Bob", "Charlie"]
scores = [92, 85, 78]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

The enumerate function wraps an iterable and produces pairs of an index counter and the value. It replaces the pattern of maintaining a separate counter variable inside a loop. The counter starts at zero by default and increments by one on each iteration, matching Python's zero-based indexing.

Together, zip and enumerate cover the two most common iteration enhancements: walking through parallel collections with zip, and tracking position with enumerate. Both return iterators, which means they produce items on demand rather than building a result list in memory, making them efficient for large data sets. The article on iterating through Python collections covers these patterns alongside plain for loops and nested iteration.

Rune AI

Rune AI

Key Insights

  • len() returns the count of items in any collection.
  • min() and max() find the smallest and largest element in any iterable of comparable items.
  • sum() totals the numeric values in any iterable.
  • sorted() returns a new sorted list from any iterable; reversed() returns a reverse iterator.
  • zip() pairs elements from multiple iterables; enumerate() pairs indices with values.
RunePowered by Rune AI

Frequently Asked Questions

Which built-in functions work on all collection types?

len() works on every collection and returns the number of items. min() and max() work on any collection whose elements are comparable. sorted() and reversed() work on any iterable and return a new sorted or reversed list or iterator. The in operator works on all collections for membership testing, though the performance varies by type.

Does sum() work on sets and dictionaries?

sum() works on any iterable of numbers, including sets, the keys of a dictionary, and the values of a dictionary. It does not work on dictionaries directly because iterating over a dictionary yields its keys, and keys may not be numbers. Use sum(my_dict.values()) to sum a dictionary's values.

What is the difference between sorted() and the list sort() method?

sorted() is a built-in function that accepts any iterable and returns a new sorted list, leaving the original unchanged. The sort() method is only available on lists, modifies the list in place, and returns None. Use sorted() when you need to preserve the original order or when working with non-list iterables. Use sort() when you do not need the original list and want to save memory.

Conclusion

Python's built-in collection functions are the common vocabulary you use to ask questions about any collection: how many items, what is the smallest, what is the largest, what is the total. They work uniformly across types, which means you learn them once and apply them everywhere.