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.
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.
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.
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
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.
Frequently Asked Questions
Which built-in functions work on all collection types?
Does sum() work on sets and dictionaries?
What is the difference between sorted() and the list sort() method?
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.
More in this topic
Nested Lists in Python
Learn how to create, access, and modify nested lists in Python. Build grids and matrices, and understand how shallow copies affect multi-dimensional data.
List Comprehensions in Python
Master Python list comprehensions to create, filter, and transform lists in a single line. Learn the syntax, common patterns, and when to use a regular loop instead.
Copy Python Lists
Learn how to copy Python lists using slicing, the copy method, the list constructor, and the copy module. Understand shallow vs deep copies.