Python Sets
A set in Python is used to store multiple values in a single variable. It is one of Python’s four built-in collection data types, along with List, Tuple, and Dictionary—each designed for different use cases.
Set
A set is a collection that is:
- Unordered – Items have no fixed position
- Unindexed – Elements cannot be accessed by index
- Unchangeable – Individual items cannot be modified
- Unique – Duplicate values are not allowed
Although set items themselves cannot be changed, you can add new items or remove existing ones.
Creating a Set
Sets are written using curly braces {}.
Characteristics of Set Items
1. Unordered
Items in a set do not follow any specific order and cannot be accessed using an index.
The order of elements may differ on each execution.
2. Unchangeable (Immutable Items)
Once a set is created, you cannot change its elements directly. However, you can remove or add items.
3. No Duplicate Values
Sets automatically remove duplicate entries.
Only unique values are stored.
Special Case: Boolean and Integer Values
In Python sets:
True is treated as 1
False is treated as 0
Here, True and 1 are considered duplicates, as are False and 0.
Finding the Length of a Set
Use the len() function to get the number of elements in a set.
Set Items and Data Types
A set can store elements of any data type.
Same Data Type
Mixed Data Types
Checking the Data Type of a Set
From Python’s perspective, sets belong to the set class.
Output:
Using the set() Constructor
You can also create a set using the built-in set() constructor.
Python Collection Data Types
Python provides four main collection types:
- List – Ordered, changeable, allows duplicates
- Tuple – Ordered, unchangeable, allows duplicates
- Set – Unordered, unindexed, no duplicates
- Dictionary – Ordered, changeable, no duplicate keys
Accessing Items in a Python Set
Unlike lists or dictionaries, sets do not support indexing or keys. This is because sets are unordered and unindexed collections.
However, you can still work with set elements in two common ways:
- Iterating through the set
- Checking membership using the in keyword
Looping Through a Set
To access each item in a set, use a for loop.
Checking if an Item Exists in a Set
You can use the in keyword to check whether a specific value is present.
This returns True if the item exists, otherwise False.
Checking if an Item Does NOT Exist
To confirm that an item is not in a set, use not in.
This returns True if the value is not present in the set.
Adding Items to a Python Set
In Python, set elements themselves cannot be modified, but you can still add new items or merge items from other collections after the set is created.
Adding a Single Item
To insert one new element into a set, use the add() method.
Adding Items from Another Set
To combine elements from one set into another, use the update() method.
All unique elements from tropical_fruits are added to fruits.
Adding Items from Any Iterable
The update() method accepts any iterable, not just sets. This includes lists, tuples, and even dictionary keys.
Example: Adding Items from a List
Key Points
- Use add() to insert one item
- Use update() to insert multiple items
- update() works with sets, lists, tuples, and other iterables
- Duplicate values are automatically ignored
Removing Items from a Python Set
Python provides several ways to remove elements from a set. The method you choose depends on whether you want error handling, random removal, or complete deletion of the set.
1. Using remove()
The remove() method deletes a specific element from the set.
Important: If the specified item does not exist, remove() raises a KeyError.
2. Using discard() (Safer Option)
The discard() method also removes a specified element, but does not raise an error if the item is missing.
3. Using pop() (Random Removal)
The pop() method removes and returns a random item from the set.
4. Using clear() (Empty the Set)
The clear() method removes all elements, leaving an empty set.
5. Using del (Delete the Set Completely)
The del keyword removes the entire set object from memory.
Looping Through Items in a Python Set
Since sets are unordered and unindexed, you cannot access their elements using index positions. Instead, Python allows you to iterate over set items using a for loop.
Using a for Loop with a Set
The most common way to read all elements in a set is by looping through it.
Example
Looping through a set is useful when performing an action on every unique item.
Key Points
- Sets do not support indexing
- Use a for loop to access elements
- Output order is not guaranteed
- Ideal for working with unique values
Joining Sets in Python
Python provides powerful set operations to combine or compare two or more sets. These operations are commonly used to find all items, common items, unique items, or non-overlapping items between sets.
Overview of Set Join Operations
- union() - Combines all unique elements
- update() - Adds elements to an existing set
- intersection() - Keeps only common elements
- difference() - Keeps elements unique to the first set
- symmetric_difference() - Keeps elements not common to both sets
Union – Combine All Elements
The union() method returns a new set containing all unique elements from both sets.
Using the | Operator
You can achieve the same result using the pipe (|) operator.
Joining Multiple Sets
Using union() with Multiple Sets:
Using Multiple | Operators
Joining a Set with Other Iterables
The union() method can also merge a set with lists or tuples. The | operator works only with sets, not other iterables.
Update – Modify the Original Set
The update() method adds elements from another set (or iterable) directly into the original set. Unlike union(), this method does not return a new set.
Intersection – Keep Common Elements Only
The intersection() method returns elements that exist in both sets.
Using the & Operator
intersection_update() – Modify Original Set
Boolean Values in Intersection
True equals 1, and False equals 0 in sets.
Difference – Keep Unique Items from the First Set
The difference() method keeps elements that are only in the first set.
Using the - Operator
difference_update() – Modify Original Set
Symmetric Difference – Exclude Common Items
The symmetric_difference() method returns elements that are not shared between sets.
Using the ^ Operator
symmetric_difference_update() – Modify Original Set
Key Takeaways
- Use union() to combine all unique elements
- Use intersection() to find common elements
- Use difference() to find unique elements
- Use symmetric_difference() to exclude duplicates
- Methods ending with _update() modify the original set
Python frozenset
A frozenset is an immutable (unchangeable) version of a set. It behaves much like a normal set, but once created, its elements cannot be modified.
What Is a Frozenset?
A frozenset has the following properties:
- Unordered – No fixed order of elements
- Unique – Duplicate values are not allowed
- Immutable – Items cannot be added or removed
Creating a Frozenset
You can create a frozenset using the built-in frozenset() constructor with any iterable (list, set, tuple, etc.).
1. copy() – Create a Copy
2. union() – Combine Elements
Shortcut operator:
3. intersection() – Common Elements
Shortcut operator:
4. difference() – Unique Elements
Shortcut operator:
5. symmetric_difference() – Non-Common Element
Shortcut operator:
6. Subset and Superset Checks
Using operators:
7. isdisjoint() – No Common Elements
Python Set Methods
Python provides a rich set of built-in methods for sets that allow you to add, remove, compare, and combine elements efficiently.
Common Set Methods with Examples
1. add() – Add One Element
Adds a single element to the set.
2. clear() – Remove All Elements
Removes every item from the set, leaving it empty.
3. copy() – Create a Copy of the Set
Returns a shallow copy of the set.
4. difference() (-) – Find Unique Elements
Returns elements that exist in the first set but not in the others.
Using the operator:
5. difference_update() (-=) – Modify the Original Set
Removes elements that are also found in another set.
6. discard() – Remove Item Without Error
Removes a specific item if it exists.
7. intersection() (&) – Common Elements
Returns a set of elements shared by all sets.
Using the operator:
8. intersection_update() (&=) – Modify the Original Set
Keeps only the elements that exist in all sets.
9. isdisjoint() – No Common Elements
Checks whether two sets share any elements.
10. issubset() (<=, <) – Subset Check
Checks if all elements of one set exist in another.
11. issuperset() (>=, >) – Superset Check
Checks if a set contains all elements of another set.
12. pop() – Remove a Random Element
Removes and returns an arbitrary element.
13. remove() – Remove Specific Item
Deletes an item but raises an error if it doesn’t exist.
14. symmetric_difference() (^) – Non-Common Elements
Returns elements that are in either set, but not in both.
Using operator:
15. symmetric_difference_update() (^=) – Modify Original Set
Keeps only non-common elements.
16. union() (|) – Combine Sets
Returns a set containing all unique elements.
Using operator:
17. update() (|=) – Modify Original Set
Adds elements from another set or iterable.
Method Operator Purpose
add() — Add one element
clear() — Remove all elements
copy() — Copy set
difference() - Unique elements
difference_update() -= Modify original
discard() — Remove safely
intersection() & Common elements
intersection_update() &= Modify original
isdisjoint() — No common items
issubset() <=, < Subset check
issuperset() >=, > Superset check
pop() — Remove random item
remove() — Remove item
symmetric_difference() ^ Non-common items
symmetric_difference_update() ^= Modify original
union() ` `
update() ` =`