A set in Python is a built-in collection used to store multiple values without keeping duplicate elements. Sets are useful when the main requirement is to work with unique values, such as removing duplicates or checking whether an element exists in a collection.
Unlike lists and tuples, sets are unordered and do not support indexing. Python also provides several operations for comparing and combining sets, making them useful for tasks involving common, different, or unique elements.
Table of Contents
What Is a Set in Python?
A set is an unordered collection of unique elements. If duplicate values are added to a set, Python automatically keeps only one occurrence of each value.
Sets are written using curly braces { }, as long as the braces contain elements.
numbers = {10, 20, 30, 40}
print(numbers)
Output:
{10, 20, 30, 40}
The order in which elements appear when a set is displayed should not be relied upon because sets are unordered collections.
Why Are Sets Used?
Sets are particularly useful when duplicate values are not required. They also provide efficient membership testing and convenient operations for comparing multiple collections.
- To Store Unique Values: Sets store only unique elements, so duplicate values are not retained.
- To Remove Duplicate Elements: You can convert a list or another iterable into a set to remove duplicate values.
- To Check Whether an Element Exists: Sets support efficient membership testing using the in and not in operators.
- To Find Common Elements: You can use set intersection to find elements that appear in two or more collections.
- To Find Elements Present in One Collection but Not Another: Set difference helps identify elements that exist in one set but not in another.
- To Combine Unique Elements from Multiple Collections: Set union combines elements from multiple sets while keeping only unique values.
Characteristics of Sets
Understanding the main characteristics of sets helps explain how they differ from other Python collections. A set behaves differently from a list or tuple because its elements are unique and it does not provide positional access.
- Unique: Duplicate elements are automatically removed.
- Unordered: Elements do not have a fixed positional order.
- Mutable: A set can be changed after it is created.
- Unindexed: Elements cannot be accessed using positions such as [0].
Creating a Set
A set can be created by placing comma-separated values inside curly braces. Python automatically treats the values as set elements and removes duplicates.
Syntax:
set_name = {element1, element2, element3}
The following example creates a set containing several integer values.
numbers = {10, 20, 30, 40}
print(numbers)
Output:
{10, 20, 30, 40}
1. Creating an Empty Set
Curly braces alone do not create an empty set in Python. The expression {} creates an empty dictionary.
To create an empty set, use the set() constructor.
numbers = set() print(numbers) print(type(numbers))
Output:
set()
<class 'set'>
Therefore, use set() whenever an empty set is required.
2. Using the set() Constructor
The set() constructor can create a set from an iterable such as a list, tuple, string, or another set. This is also a common way to convert another collection into a set.
Syntax:
set(iterable)
For example, a list can be converted into a set.
values = [10, 20, 20, 30, 30, 40] numbers = set(values) print(numbers)
Output:
{10, 20, 30, 40}
The duplicate values from the list are removed when the list is converted into a set.
3. Creating a Set from a List
A list can contain duplicate values and maintains an order, while a set keeps only unique values and does not provide positional ordering.
numbers = [10, 20, 10, 30, 20, 40] unique_numbers = set(numbers) print(unique_numbers)
Output:
{10, 20, 30, 40}
This makes sets useful for removing duplicate values from a list.
4. Creating a Set from a Tuple
A tuple can also be converted into a set using set(). Any duplicate values in the tuple are removed during the conversion.
values = (10, 20, 10, 30, 20) numbers = set(values) print(numbers)
Output:
{10, 20, 30}
5. Creating a Set from a String
A string is an iterable, so it can also be passed to set(). In this case, the resulting set contains the unique characters from the string.
text = "banana" characters = set(text) print(characters)
Output:
{'b', 'a', 'n'}
The exact display order may vary because a set is unordered.
Duplicate Elements in a Set
Sets automatically eliminate duplicate values. When the same value occurs multiple times, the set stores only one occurrence.
numbers = {10, 20, 20, 30, 10, 40}
print(numbers)
print(len(numbers))
Output:
{10, 20, 30, 40}
4
Although six values were written when creating the set, only four unique values remain.
Accessing Set Elements
Sets do not support indexing because their elements are not arranged as a sequence with fixed positions. Therefore, expressions such as numbers[0] cannot be used to access a set element.
The normal way to work with individual elements of a set is to iterate over it.
numbers = {10, 20, 30, 40}
for number in numbers:
print(number)
Output:
10
30
20
40
The output order may vary because sets do not guarantee a particular iteration order.
Checking Membership in a Set
Membership testing checks whether a particular value exists in a set. Python provides the in and not in operators for this purpose.
Syntax:
element in set_name
The following example checks whether specific values are present in a set.
numbers = {10, 20, 30, 40}
print(20 in numbers)
print(50 in numbers)
print(50 not in numbers)
Output:
True
False
True
Membership testing is one of the important use cases for sets because sets are designed to perform membership checks efficiently.
Finding the Length of a Set
The built-in len() function returns the number of unique elements currently stored in a set.
Syntax:
len(set_name)
numbers = {10, 20, 20, 30, 40}
print(len(numbers))
Output:
4
The duplicate value 20 is counted only once.
Basic Set Operations
Sets provide operations for combining collections and finding relationships between them. These operations are especially useful when working with unique groups of values.
Python provides operators for the four fundamental set operations:
- union
- intersection
- difference
- symmetric difference.
1. Union of Sets
The union of two sets contains all unique elements that appear in either set. The union operator is the vertical bar |.
Syntax:
set1 | set2
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1 | set2
print(result)
Output:
{1, 2, 3, 4, 5, 6}
The common elements appear only once in the resulting set.
2. Intersection of Sets
The intersection contains only the elements that are present in both sets. The intersection operator is the ampersand &.
Syntax:
set1 & set2
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1 & set2
print(result)
Output:
{3, 4}
Only the values common to both sets are included.
3. Difference of Sets
The difference operation returns elements that exist in the first set but not in the second set. The difference operator is the hyphen -.
Syntax:
set1 - set2
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1 - set2
print(result)
Output:
{1, 2}
The result contains values that belong to set1 but not to set2.
4. Symmetric Difference of Sets
The symmetric difference contains elements that belong to either set but not to both. The symmetric difference operator is the caret ^.
Syntax:
set1 ^ set2
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1 ^ set2
print(result)
Output:
{1, 2, 5, 6}
The common elements 3 and 4 are excluded from the result.
Combining Basic Set Operations
Set operators can be combined to solve more practical collection problems. The following example uses several basic operations to compare two groups of values.
python_students = {"A", "B", "C", "D"}
java_students = {"C", "D", "E", "F"}
all_students = python_students | java_students
both_courses = python_students & java_students
only_python = python_students - java_students
print(all_students)
print(both_courses)
print(only_python)
Output:
{'A', 'B', 'C', 'D', 'E', 'F'}
{'C', 'D'}
{'A', 'B'}
Here, the union finds all students, the intersection finds students in both groups, and the difference finds students who are only in the first group.
Converting Sets to Other Collections
A set can be converted into another collection type when ordered or indexed access is required. Common conversions include converting a set to a list or tuple.
numbers = {10, 20, 30, 40}
numbers_list = list(numbers)
numbers_tuple = tuple(numbers)
print(type(numbers_list))
print(type(numbers_tuple))
Output:
<class 'list'>
<class 'tuple'>
Because the original set is unordered, the resulting list or tuple should not be assumed to follow a particular order unless you explicitly sort it.
Set vs List
Both sets and lists can store multiple values, but they are designed for different purposes. Lists maintain sequence and allow duplicate values, while sets focus on uniqueness and membership operations.
| Feature | Set | List |
|---|---|---|
| Duplicates | Not allowed | Allowed |
| Ordering | Unordered | Ordered |
| Indexing | Not supported | Supported |
| Mutable | Yes | Yes |
| Membership testing | Efficient | Generally slower for large collections |
Set vs Tuple
Sets and tuples both store collections of values, but tuples are ordered and immutable, whereas sets are unordered and designed around unique elements.
| Feature | Set | Tuple |
|---|---|---|
| Duplicates | Not allowed | Allowed |
| Ordering | Unordered | Ordered |
| Indexing | Not supported | Supported |
| Mutability | Mutable | Immutable |
| Main use | Unique values and set operations | Fixed collections of values |
Set vs Dictionary
Sets and dictionaries both use curly braces, but they represent different types of collections. A set stores individual values, while a dictionary stores key-value pairs.
| Feature | Set | Dictionary |
|---|---|---|
| Stores | Unique values | Key-value pairs |
| Syntax | {1, 2, 3} | {"a": 1, "b": 2} |
| Duplicate values | Not stored | Values can be duplicated |
| Keys | Not applicable | Keys must be unique |
| Access | Membership testing/iteration | Key-based access |
Practical Examples of Sets
Sets are useful in practical programming whenever a collection should contain unique values. The following examples demonstrate common situations where sets provide a simple solution.
1. Removing Duplicate Values
One common use of a set is removing duplicates from a list. Converting the list to a set automatically keeps only unique values.
numbers = [10, 20, 10, 30, 20, 40, 30] unique_numbers = set(numbers) print(unique_numbers)
Output:
{10, 20, 30, 40}
2. Finding Common Values
The intersection operator can be used when two collections need to be compared to find values common to both.
group_a = {"Python", "Java", "C++"}
group_b = {"Java", "C++", "JavaScript"}
common = group_a & group_b
print(common)
Output:
{'Java', 'C++'}
3. Finding Unique Values Between Groups
The symmetric difference operator is useful when values shared by both groups should be excluded.
group_a = {"A", "B", "C"}
group_b = {"B", "C", "D"}
unique = group_a ^ group_b
print(unique)
Output:
{'A', 'D'}
Edge Cases
Sets have a few behaviors that can cause unexpected results if their rules are not understood. Paying attention to empty sets, duplicate values, indexing, and element types helps avoid common problems.
- Using {} to Create an Empty Set: Writing {} creates an empty dictionary, not an empty set. Use set() to create an empty set.
- Duplicate Values Are Automatically Removed: Sets keep only unique elements, so repeated values are stored only once.
- Accessing Elements Using Indexes: Sets do not support indexing because they are unordered collections. You cannot access an element using an expression such as my_set[0].
- Adding Mutable Objects to a Set: Mutable objects such as lists and dictionaries cannot be stored directly as set elements because they are unhashable.
- Relying on the Order of Elements: Sets do not guarantee a meaningful element order. Avoid writing code that depends on the order in which elements appear.
- Converting a Set to a List: Converting a set to a list does not create a meaningful or guaranteed order. If you need a consistent order, use sorted() to obtain a sorted list when the elements can be compared.
Common Mistakes
Most beginner mistakes with sets come from treating them like lists or dictionaries. The following points cover the most common situations to avoid.
- Using {} to Create an Empty Set: Writing {} creates an empty dictionary instead of an empty set. Use set() when you need to create an empty set.
- Accessing Set Elements Using Indexing: Sets do not support indexing, so expressions such as numbers[0] raise a TypeError.
- Expecting Sets to Preserve Insertion Order: Sets do not guarantee insertion order, so you should not rely on elements appearing in the order in which they were added.
- Expecting Duplicate Values to Remain: Sets automatically remove duplicate values, so repeated elements are stored only once.
- Adding Lists or Dictionaries Directly to a Set: Lists and dictionaries are mutable and unhashable, so they cannot be added directly as set elements.
- Assuming Converting a Set to a List Restores the Original Order: Converting a set to a list does not recover the order in which the elements were originally inserted. Use sorted() if you need a consistent sorted order.
Important Rules for Sets
The following rules summarize the behavior that should be remembered when working with sets in Python.
- A set stores unique elements.
- A set is mutable.
- Sets do not support indexing or slicing.
- Use set() to create an empty set.
- Use in and not in for membership testing.
- Use | for union.
- Use & for intersection.
- Use - for difference.
- Use ^ for symmetric difference.
- Do not depend on the display or iteration order of a set.
Quick Reference Table
The following table provides a quick overview of the fundamental set concepts and operations discussed in this article.
| Concept | Syntax / Example | Purpose |
|---|---|---|
| Create a set | {1, 2, 3} | Create a set with elements |
| Empty set | set() | Create an empty set |
| Convert iterable | set(iterable) | Create a set from an iterable |
| Length | len(s) | Count unique elements |
| Membership | x in s | Check whether an element exists |
| Union | s1 | s2 | All unique elements from both sets |
| Intersection | s1 & s2 | Elements common to both sets |
| Difference | s1 - s2 | Elements in the first set but not the second |
| Symmetric difference | s1 ^ s2 | Elements in either set but not both |
Conclusion
Sets in Python provide a convenient way to work with unique values. They are especially useful for removing duplicates, testing membership, and comparing groups of data.
Unlike lists and tuples, sets do not support indexing and should not be treated as ordered sequences. Once the basic behavior of sets is understood, set methods can be used to add, remove, update, and compare elements in more detailed ways.
For a detailed explanation of individual operations such as add(), update(), remove(), discard(), union(), intersection(), and other set methods, see the Set Methods in Python article.
Frequently Asked Questions (FAQs)
Here are some common questions beginners may have when working with sets in Python. These questions cover the basic concepts, behavior, and common uses of sets.
1. What is a set in Python?
A set is a collection used to store unique elements in Python. It does not allow duplicate values and does not support positional indexing.
2. How do you create a set in Python?
A set can be created by placing elements inside curly braces, such as {1, 2, 3}. You can also use the set() constructor to create a set from an iterable.
3. How do you create an empty set in Python?
Use set() to create an empty set. The expression {} creates an empty dictionary, not an empty set.
4. Can a set contain duplicate elements?
No, a set stores only unique elements. If duplicate values are provided while creating a set, Python automatically keeps only one occurrence of each value.
5. Can you access set elements using indexing?
No, sets do not support indexing or slicing because they are unordered collections without fixed positions. You can instead iterate over the set using a for loop or check whether a value exists using membership operators.
0 Comments