Guide Python Beginner

12.9 Built-in Functions

The same general-purpose sequence functions used with lists and tuples -- len, max, min, sum, sorted, any, all -- work identically on sets, with sorted() always returning a list since a set has no order to sort in place.

2 min read

The same general-purpose functions used with lists (see 10.8 Built-in Functions) and tuples (see 11.7 Built-in Functions and Traversal) work identically on sets.

>>> len({3, 1, 4, 1, 5})
4
>>> max({3, 1, 4, 1, 5}), min({3, 1, 4, 1, 5})
(5, 1)
>>> sum({3, 1, 4, 1, 5})
13
>>> any({0, 0, 1}), all({1, 1, 1})
(True, True)

sorted()

Always returns a list — sets have no inherent order to sort in place.

>>> sorted({3, 1, 4, 1, 5})
[1, 3, 4, 5]

Quick Interview Answer

“Every general-purpose sequence function — len, max, min, sum, any, all — works on a set exactly as it does on a list or tuple, since none of them depend on order or indexing, only on iteration and comparison. sorted() is worth calling out specifically: it always returns a list, never a set, both because there’s no such thing as an in-place set.sort() and because the very concept of ‘sorted’ requires an order a set doesn’t have.”

Common Mistakes

  • Expecting sorted(some_set) to return a set — it always returns a list; wrap in set(sorted(...)) only if a set is genuinely needed afterward (which discards the ordering again).
  • Calling max()/min() on a set containing mixed, non-comparable types (like str and int together) — raises TypeError, same as it would for a list.
  • Forgetting sum() on a set of non-numeric hashable values (like strings) raises TypeError — sum() requires numeric elements, regardless of container type.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form