Sub topic 2
Creating sets
This chapter covers the ways to build a set in Python: literals, the set() constructor, comprehensions, and conversion from other collections. It also covers the empty-set trap and what happens to duplicates and order. It assumes you know basic Python syntax and variables, and that you are comfortable with lists, tuples, dictionaries, for loops, the in operator, and the difference between mutable and immutable objects.
What you get when you create a set
A set is an unordered collection of unique, hashable elements. Every way of creating one ends with the same result: duplicates are removed, and the elements have no position. You cannot index a set (s[0] raises TypeError), and the order you see when printing it is an implementation detail you should not rely on.
There are four common ways to create a set:
| Way | Example | Best for |
|---|---|---|
| Literal | `{1, 2, 3}` | A few known values |
| `set()` with no argument | `set()` | An empty set |
| `set(iterable)` | `set("hello")` | Converting an existing collection |
| Comprehension | `{n * n for n in data}` | Building from an expression or filter |
The sections below take these in turn.
Set literals
A set literal uses curly braces around comma-separated values. Duplicates are dropped as the set is built.
fruits = {"apple", "banana", "apple"}
print(len(fruits)) # 2, duplicates are dropped
print("apple" in fruits) # TrueThe literal {"apple", "banana", "apple"} does not raise an error for the repeated value. The second "apple" is compared with the first, found equal, and ignored.
Equality decides what counts as a duplicate. In Python, 1, 1.0, and True are equal and have the same hash, so they collapse into one element:
mixed = {1, 1.0, True, "1"}
print(len(mixed)) # 2, because 1, 1.0 and True are the same element
print("1" in mixed) # True, the string "1" is a different valueThe element that stays is the first one inserted. Here that is the integer 1. This surprises people who mix numbers and booleans in one set, so keep the types consistent.
The empty set trap
An empty pair of braces does not create an empty set. It creates an empty dictionary, because dictionaries used the {} syntax first.
empty = set() # the only way to write an empty set
print(type({})) # <class 'dict'>
print(type(empty)) # <class 'set'>
print(len(empty)) # 0This is the most common mistake when creating sets. The error often appears later, when you call .add() on what you thought was a set:
seen = {}
try:
seen.add(1)
except AttributeError as e:
print(e) # 'dict' object has no attribute 'add'The set() constructor
The set() constructor takes any iterable and returns a new set of its distinct elements. An iterable is any object you can loop over with for.
letters = set("hello")
print(len(letters)) # 4, because 'l' appears twice
print(sorted(letters)) # ['e', 'h', 'l', 'o']
from_list = set([3, 1, 2, 3, 1])
print(sorted(from_list)) # [1, 2, 3]
from_tuple = set((10, 20, 10))
print(sorted(from_tuple)) # [10, 20]
from_range = set(range(5))
print(sorted(from_range)) # [0, 1, 2, 3, 4]A string is an iterable of characters, so set("hello") gives a set of single-character strings. If you wanted a set holding the whole word, use a literal or wrap it in a list: {"hello"} or set(["hello"]).
set() accepts at most one argument. Passing several values is an error:
try:
set(1, 2, 3)
except TypeError as e:
print(e) # set expected at most 1 argument, got 3Passing a single non-iterable value fails too:
try:
set(5)
except TypeError as e:
print(e) # 'int' object is not iterableConverting from a dictionary
Iterating over a dictionary yields its keys, so set(d) gives the set of keys. Use .values() or .items() to build sets from the other parts.
ages = {"ann": 31, "bob": 25, "cy": 31}
print(sorted(set(ages))) # ['ann', 'bob', 'cy']
print(sorted(set(ages.values()))) # [25, 31]
print(sorted(set(ages.items()))) # [('ann', 31), ('bob', 25), ('cy', 31)]The .items() version works because each item is a tuple, and tuples of hashable values are hashable. The next chapter section on hashability explains why this matters.
Copying a set
Passing a set to set() makes a shallow copy. The new set is a separate object, so changing it does not change the original.
original = {1, 2, 3}
copy = set(original)
copy.add(4)
print(sorted(original)) # [1, 2, 3]
print(sorted(copy)) # [1, 2, 3, 4]The .copy() method does the same thing. Assigning with = does not copy. It only gives the same set a second name.
Elements must be hashable
Whatever way you use to create a set, every element must be hashable. Hashable objects are immutable (or at least define a stable hash), such as numbers, strings, and tuples of hashable values. Lists, dicts, and sets are mutable and are not hashable.
points = {(1, 2), (3, 4)} # tuples are hashable
print((1, 2) in points) # True
try:
bad = {[1, 2], [3, 4]} # lists are not hashable
except TypeError as e:
print(e) # unhashable type: 'list'The same rule applies to set(). Converting a list of lists fails, and converting a list of tuples works:
rows = [[1, 2], [3, 4]]
try:
set(rows)
except TypeError as e:
print(e) # unhashable type: 'list'
print(sorted(set(tuple(r) for r in rows))) # [(1, 2), (3, 4)]A tuple is only hashable if everything inside it is hashable. (1, [2]) raises the same TypeError when you try to put it in a set. A set of sets also fails with a literal, because sets are mutable. The fix is frozenset, covered in a later chapter.
Set comprehensions
A set comprehension has the same shape as a list comprehension but uses braces. It builds a set from an expression, with an optional if filter.
squares = {n * n for n in range(-3, 4)}
print(sorted(squares)) # [0, 1, 4, 9]The input range has seven values, but the result has four. Squaring -3 and 3 gives the same number, and the set keeps one copy. A list comprehension would have kept all seven.
Adding a condition filters the input:
words = ["Apple", "apple", "Banana", "cherry", "BANANA"]
lowered = {w.lower() for w in words if len(w) > 5}
print(sorted(lowered)) # ['banana']Here only the 6-letter words pass the filter (Banana and BANANA), and lowercasing makes them equal, so one element remains. Comprehensions are a good fit when you need to normalize values and remove duplicates in one step.
Dropping duplicates while keeping order
Converting a list to a set removes duplicates but loses the original order. If order matters, use dict.fromkeys(). Dictionaries keep insertion order, and their keys are unique.
items = ["b", "a", "b", "c", "a"]
unique_any_order = set(items)
print(len(unique_any_order)) # 3
unique_in_order = list(dict.fromkeys(items))
print(unique_in_order) # ['b', 'a', 'c']dict.fromkeys(items) builds a dict whose keys are the items, which removes duplicates and keeps the first-seen order. Calling list() on it gives back a list of those keys. The result is a list, not a set. Use this when you want a deduplicated sequence, and use set() when you need set operations or fast membership tests.
Order is not part of the contract
When you create a set and print it, the elements appear in some order. That order depends on the hash values and the internal table layout. For small integers it often looks sorted, which makes it tempting to rely on it. Do not.
s = {3, 1, 2}
print(s) # often {1, 2, 3}, but this is not guaranteedString hashes are randomized per process, so a set of strings can print in a different order on each run. Code that depends on set order will pass tests one day and fail the next. When you need a stable order for output or comparison, wrap the set in sorted():
tags = {"python", "sets", "hash"}
print(sorted(tags)) # ['hash', 'python', 'sets']The examples in this tutorial use sorted() for the same reason.
Choosing how to create a set
The right form depends on where your data comes from.
- Use a literal when you know the values when you write the code:
{"red", "green", "blue"}. - Use
set()for an empty set, and for converting an existing list, tuple, string, range, dict, or file lines. - Use a comprehension when each element comes from an expression or a filter.
- Use
dict.fromkeys()followed bylist()when you need to remove duplicates and keep order.
Common errors when creating sets
- Writing
{}for an empty set. You get a dict, and later.add()fails withAttributeError. - Passing several arguments to
set(), as inset(1, 2, 3). Pass one iterable:set([1, 2, 3]), or use the literal{1, 2, 3}. - Passing a string when you meant a single element.
set("cat")gives{'c', 'a', 't'}, while{"cat"}gives a set with one string. - Including a list, dict, or set as an element. The result is
TypeError: unhashable type. Convert lists to tuples first. - Expecting
1andTrue, or1and1.0, to stay separate. They are equal, so only one remains. - Expecting the result to keep the order of the input. Use
dict.fromkeys()if you need that.
Exercise
What does each line print? a = {}, b = set(), c = {1, 2, 2, 3}, d = set("noon"). Give type(a), type(b), len(c) and len(d).
Show answer
type(a) is <class 'dict'> because empty braces make a dict. type(b) is <class 'set'>. len(c) is 3 because the duplicate 2 is dropped. len(d) is 2 because the characters of "noon" are n, o, o, n, which leave only the two distinct characters 'n' and 'o'.
Exercise
You have data = ["x", "y", "x", "z", "y"]. Write one expression that gives a list of the distinct values in the order they first appear, and explain why list(set(data)) is not a safe substitute.
Show answer
list(dict.fromkeys(data)) gives ['x', 'y', 'z']. Dictionary keys are unique and keep insertion order. list(set(data)) also removes duplicates, but a set has no guaranteed order, and string hashes vary between runs, so the result can come out in a different order each time.
Exercise
Why does set([[1, 2], [3, 4]]) raise a TypeError, and how do you build a set from those two inner lists?
Show answer
Lists are mutable and therefore not hashable, and set elements must be hashable. Convert each inner list to a tuple: set(tuple(r) for r in [[1, 2], [3, 4]]) gives {(1, 2), (3, 4)}.