Creating Sets

Concepts covered: Sets

Write braces around values when you know the values while writing the code. Call the set() function on an iterable when the values already live in some other collection and you want its distinct members.

Braces around known values

weekend = {"sat", "sun"}
primes = {2, 3, 5, 7, 7, 5}
print(len(weekend))
print(primes)
print("sun" in weekend)

Output:

2
{2, 3, 5, 7}
True

Each value appears once in the result whether you typed it once or twice. Writing {2, 3, 5, 7} and {7, 5, 3, 2, 2} produces equal sets, because a set is defined by its members alone, never by how many times or in what order they were listed.

The empty set is set(), never {}

Braces reached Python as dictionary syntax first, so empty braces produce an empty dictionary. There's no brace spelling for a set with nothing in it. Call set() with no argument, and read the type back whenever you doubt which one you are holding.

empty_braces = {}
empty_set = set()
print(type(empty_braces) == dict)
print(type(empty_set) == set)
print(len(empty_set))
print(empty_set)

Output:

True
True
0
set()

Printing an empty set shows set() rather than braces, for the same reason: braces with nothing between them would read as a dictionary. You'll see this spelling again whenever a set runs out of members.

set() walks any iterable

An iterable is anything a for loop can step through: a list, a string, a range, a dictionary. set() steps through it the same way and adds each item it meets. Repeats collapse as they arrive. A dictionary contributes its keys, because keys are what a for loop over a dictionary yields.

orders = [12, 7, 12, 3, 7, 7]
print(set(orders))
print(set(range(4)))
print(len(set("mississippi")))
stock = {"pen": 40, "ink": 0, "pad": 12}
print(set(stock) == {"pen", "ink", "pad"})

Output:

{3, 12, 7}
{0, 1, 2, 3}
4
True

The list [12, 7, 12, 3, 7, 7] became {3, 12, 7}: 3 distinct values survived, and the printed order matches neither the list nor numeric order. That order is the storage layout, nothing more. The string "mississippi" has 11 characters but only 4 distinct letters, m, i, s, p. The dictionary gave up its 3 keys and none of its values.

SourceWhat set() steps throughResult
`[1, 1, 2]`Each list item`{1, 2}`
`"aab"`Each character`{"a", "b"}`
`range(3)`0, 1, 2`{0, 1, 2}`
`{"x": 1, "y": 2}`The keys only`{"x", "y"}`
`42`Nothing: an integer has no items`TypeError`
print(set(42))

An integer is a single value with nothing to step through, so set(42) has no items to collect and Python says so. Either {42} or set([42]) makes a set holding 42, because each gives set() something it can walk.

One string or its characters?

{"hello"} has 1 member, the whole word. set("hello") has 4 members, one per distinct letter: h, e, l, o. Both are valid, and they answer different questions, so pick the spelling that matches the question you are asking.

word_set = {"hello"}
char_set = set("hello")
print(len(word_set))
print(len(char_set))
print("hello" in word_set, "hello" in char_set)
print("h" in word_set, "h" in char_set)

Output:

1
4
True False
False True

What does this line print?

print(len(set([1, 2, 3])), len({1, 2, 3}), len(set("123")))

The 2 sources you will turn into sets most often are a list of raw records and a dictionary used as a lookup. Both go through the same set() call, and the results compare directly, because a set built from a dictionary holds plain keys.

prices = {"A1": 3.5, "B2": 4.0, "C3": 2.25}
basket = ["B2", "D4", "B2", "A1"]
basket_codes = set(basket)
price_codes = set(prices)
print(len(basket_codes))
print("D4" in price_codes)

This prints 3 and then False. The basket names 4 codes with "B2" twice, so 3 distinct codes remain. The prices never made it into price_codes; it holds only the keys "A1", "B2" and "C3". So "D4" fails the test, and the program has found an item it can't charge for.

About this lesson

This section is part of the Sets: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.