VMware ESXi and vSphere Cluster Management
What Are Sets in Python?
Learn how Python sets store unique values, remove duplicates automatically, handle unordered data, and differ from lists.
A set is a Python collection used to store distinct values. Each value inside a set is called a member. Sets are useful when you care about whether a value exists and want each value to appear only once.
Common uses include keeping unique names, categories, tags, or identifiers. For example, a set can represent all unique tags assigned to a group of articles.
Creating a Set
A set literal is a set written with curly braces and comma-separated values. Assign the literal to a variable just as you would assign a list or another value.
names = {'Maria', 'Lucy', 'Angelina', 'Tanya'}
print(names)
Curly braces containing values create a set. The printed result contains the four names, but its display order is not guaranteed.
Sets Automatically Remove Duplicates
A duplicate is a repeated value. Sets retain only one member for each unique value, so you do not need to check manually for duplicates.
names = {'Angelina', 'Tanya', 'Maria', 'Lucy', 'Angelina', 'Tanya'}
print(names)
The input contains six values, but the resulting set has only four members: one Angelina, one Tanya, one Maria, and one Lucy. Duplicate values collapse into one member as the set is created.
Sets Are Unordered
Unordered means that set members do not have a dependable positional sequence. A set does not promise to preserve insertion order in the way a list is used to represent an ordered sequence.
Because sets have no dependable positions, you cannot retrieve a member with a numeric index:
colors = {'red', 'blue', 'green'}
# colors[0] # TypeError: sets are not indexable
Use a list when stable order or index-based access is required. Use a set when uniqueness and membership are more important than position.
Set Properties at a Glance
| Property | Behavior | Beginner takeaway |
|---|---|---|
| Duplicates | Repeated values collapse into one member. | A set stores unique values. |
| Ordering | Members do not have a dependable positional order. | Do not rely on printed order. |
| Indexing | Numeric indexes are not supported. | Use a list for position-based access. |
| Supported member types | Members must be hashable, such as strings and numbers. | Not every Python object can be placed in a set. |
| Empty-set syntax | {} creates an empty dictionary; set() creates an empty set. | Use set() for an empty set. |
List Versus Set
| Feature | List | Set |
|---|---|---|
| Duplicate values | Preserves duplicates. | Stores each value once. |
| Order | Preserves a sequence and its positions. | Does not provide a dependable positional order. |
| Index-based access | Supported, such as items[0]. | Not supported. |
| Typical use case | Keeping an ordered collection, including repeated values. | Keeping unique names, tags, categories, or identifiers. |
Set Members and Hashability
Set members must be hashable. A hashable value is suitable for use as a set member because its hash remains stable while the value is in the set. Strings and numbers are suitable introductory examples:
values = {'python', 'sets', 10, 25}
A mutable collection such as a list cannot be a set member because its contents can change:
# invalid_members = {[1, 2], [3, 4]} # TypeError: unhashable type: 'list'
This requirement helps Python locate and distinguish set members. At this level, remember that strings, integers, and other immutable values are common choices, while lists cannot be placed directly inside a set.
Changing Set Membership
Unlike a list, a set is not edited by selecting an existing item at a numeric position. Since there are no positions, you cannot replace “the item at index 0.” Set changes are instead understood as changing membership: adding a value or removing a value.
The details of adding and removing members come next, but the key distinction is:
- Changing an existing indexed item: a list operation.
- Adding or removing a member: the way set contents are changed.
Inspecting a Set
Print a set by passing its variable to print():
tags = {'python', 'beginner', 'collections'}
print(tags)
The output may display the members in an order different from the literal. Treat the order as an implementation detail, not as data you can depend on.
Use the built-in len() function to count members. len() returns the number of values in a collection, so with a set it counts distinct members:
names = {'Angelina', 'Tanya', 'Maria', 'Lucy', 'Angelina', 'Tanya'}
unique_count = len(names)
print(unique_count) # 4
The original input mentioned six names, but len(names) returns 4 because the set contains four unique values.
Creating an Empty Set
An empty pair of curly braces does not create an empty set:
empty_dictionary = {}
empty_set = set()
Python reserves {} for an empty dictionary. Use the set() constructor when you need a set with no members yet.
Troubleshooting Common Set Questions
The displayed order differs from the order in my code
This is expected because sets are unordered collections. Do not rely on print order or numeric positions. Choose a list when stable positional ordering is required.
A repeated value does not appear multiple times
That is the defining uniqueness behavior of a set. Use a list instead if retaining every occurrence is important.
Why did {} create the wrong type?
An empty pair of curly braces means an empty dictionary. Write set() to create an empty set.
Why does indexing fail?
Sets have no positional indexes. Use membership testing with in, or choose a list when you need access by position.
Why can’t I put a list inside a set?
Lists are mutable and therefore unhashable. Use hashable values such as strings, numbers, or tuples containing hashable items.
Key Points
- A set is a collection of unique, hashable values.
- Curly braces containing comma-separated values create a set literal.
- Repeated values are automatically stored only once.
- Sets are unordered, so their printed order is not dependable.
- Sets do not support numeric indexing.
- Use
len()to count distinct members. - Use
set(), not{}, to create an empty set.
Continue exploring Python sets with membership testing, adding and removing members, and set operations.