liveBook · Manning

Set

As explained in Software Engineering for Data Scientists

A set is an unordered collection of distinct elements that supports efficient membership testing and set operations.

A set is an unordered collection of distinct values. In Python, it is useful when the main question is whether a value exists in a collection, rather than which position holds it. section 6.4.1

Lists may search element by element, while sets support constant-time, or O(1), membership lookups. This difference becomes important when a collection is large or checked repeatedly. section 6.4.1 section 6.7

Compare membership-check speed

Create a large collection, then test whether 1000 is present: `nums_list = list(range(100000000))` takes about 0.003479 seconds, while `nums_set = set(range(100000000))` takes about 0.000438 seconds in the supplied timing example. The set lookup is nearly eight times faster. Sets cannot contain duplicate values, so use a list when duplicates must be preserved. section 6.4.1

Listing 6.21 This code creates a sample list with 100 million values. Then, it checks whether a sample value exists within the list, printing out the time it takes to perform the check.
import time #1

nums_list = list(range(100000000)) #2

start = time.time()
print(1000 in nums_list) #3
end = time.time()
print(end - start) #4

Inspect the Python listing that builds a 100-million-value list and measures one membership check. section 6.4.1

Use a set when the collection is static and membership checks are frequent. For practice, find artist names beginning with a, e, i, o, or u using both a list and a set, then compare their runtimes. section 6.4.1 section 6.6

How Software Engineering for Data Scientists covers it

How deep it goes
Explains list-versus-set lookup behavior, O(1) and O(n) runtimes, benchmark results, and duplicate limits.
Examples
Uses 100-million-integer timing listings and an artist-name exercise comparing list and set searches.
What it assumes
Assumes basic Python collections and membership checks while explaining lookup behavior from the list comparison onward.
What you can do after
Apply Python sets to accelerate repeated membership checks and compare their runtime with lists.
How it connects
Contrasts sets with lists and dictionaries while connecting them to computational efficiency and caching.

Also explained in

Compare how 19 books explain set →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Engineering for Data Scientists. The section links point to the parts of the book it draws on.