Sets
A set in Python is an unordered collection of unique elements. Sets store multiple items in a single variable and automatically eliminate duplicates. Unlike lists or tuples, sets do not maintain insertion order and cannot contain mutable objects such as lists or dictionaries. Sets are particularly useful for membership testing, eliminating duplicates from sequences, and performing mathematical set operations such as union, intersection, and difference.
Sets are implemented using hash tables, which allows for highly efficient operations, especially when working with large data collections.
Syntax
# Creating a set using curly braces
my_set = {element1, element2, element3}
# Creating a set using the set() constructor
my_set = set(iterable)
Parameters:
elements
: Items of any immutable data typeiterable
: Any iterable object (list, tuple, string, etc.)
Return Value:
- Returns a set object containing unique, unordered elements from the input.
Example - Basic usage of set
This example demonstrates how to create and use a set in Python, and how it automatically removes duplicate values.
# Create a set using curly bracesnumbers = {1, 2, 3, 4, 5, 2, 3}print(numbers)# Check if an element exists in the setprint(2 in numbers)print(10 in numbers)# Create a set using the set() constructor with a listfruits = set(["apple", "banana", "cherry", "apple"])print(fruits)
This example will generate the following output:
{1, 2, 3, 4, 5}TrueFalse{'apple', 'banana', 'cherry'}
Codebyte Example
In the example below, sets are created with lists and the set()
function. The following observations can be made:
- When the
animals
set is initialized without parameters, the empty set is displayed asset()
. - The
dog_breeds
set contains duplicates, but only one instance of each value is retained when printed.
Frequently Asked Questions
1. What is the difference between set and list in Python?
Sets are unordered collections of unique elements, while lists are ordered collections that can contain duplicate elements. Sets are faster for membership testing (checking if an element exists) due to their hash-based implementation. Lists maintain insertion order and allow indexed access to elements, whereas sets do not support indexing or slicing. Lists can contain any data type including mutable objects, while sets can only contain immutable (hashable) objects.
2. Is set mutable or immutable in Python?
Sets in Python are mutable, meaning you can add or remove elements after creation using methods like .add()
, .remove()
, .discard()
, .update()
, and .clear()
. If you need an immutable version of a set, you can use a frozenset, which has the same characteristics as a set but cannot be modified after creation.
3. Do sets have indexes?
No, sets in Python do not have indexes. Since sets are unordered collections, they do not support indexing, slicing, or other sequence-like operations. You cannot access set elements by position. If you need to access elements by index, you should use a list or tuple instead. To iterate through all elements in a set, you can use a for loop.
Sets
- .add()
- Adds a specified single element to a set.
- .clear()
- Removes all elements from a set.
- .copy()
- Returns a shallow copy of a specified set.
- .difference()
- Returns a new set of objects unique to a given set when compared to others.
- .difference_update()
- Modifies a set by removing all elements present in another set.
- .discard()
- Removes a specified element from a set.
- .intersection()
- Returns a new set with objects that exist inside two or more sets.
- .isdisjoint()
- Checks whether two sets contain a common element in them.
- .issubset()
- Checks whether all elements in one set exist within another specified set.
- .issuperset()
- Checks whether all elements of the specified set exist in the original set.
- .pop()
- Removes and returns a randomly chosen element from a set.
- .remove()
- Removes the specified element from a set.
- .symmetric_difference()
- Returns elements that occur in either of the two sets but not in both.
- .symmetric_difference_update()
- Updates the original set by removing items present in both sets and adding items unique to each set.
- .union()
- Returns a new set that combines objects from all sets involved, removing any duplicates.
- .update()
- Updates the original set by adding elements from another set.
- frozenset()
- Returns a new set or frozenset object whose elements are picked from a given iterable.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours