Contents:
- What is a set in Python
- What objects can be added to a set
- Creating sets
- How to add elements to a set
- Removing elements from a set
- Operations on mathematical sets
- How to check if elements are in sets
- Comparing sets
- How to check if an element belongs to a set
- How to check if one set is a subset of another
- What to remember

Course with employment: "The Python Developer Profession"
Learn moreWe continue to study data structures in Python. In previous materials, we looked at lists and tuples. In this article, we will focus on sets. We will discuss their purpose, methods of creation and key differences from other data types in Python. Sets are a useful tool for working with unique values, making them effective for solving problems involving duplicate removal and mathematical operations such as union and intersection.
Website navigation plays a key role in creating a convenient user experience. It helps visitors quickly find the information they need and navigate between pages. A proper navigation structure improves search engine indexing, which in turn can increase your site's visibility in search results. Effective navigation includes logical menu placement, clear and understandable menu item labels, and mobile-friendliness. Optimized navigation not only keeps users on the site but also increases their time on page, which positively impacts SEO rankings. It is important to regularly analyze user behavior and make changes to the navigation to keep it relevant and usable.
- What is a set in Python
- How to create one
- How to add an element
- How to remove an element
- Operations on mathematical sets
- How to check for the presence of an element
- How to compare sets with each other
- How to check if an element belongs to a set
- How to check if one set is a subset of another

Chief Programmer, Skillbox expert in backend and Java for corporate solutions. Possesses deep knowledge and experience in developing complex systems, performance optimization and implementation of modern technologies in the corporate environment. Specializes in building efficient, scalable, and reliable applications that meet demanding business requirements.
What is a Set in Python
A set is a mutable collection of unique and unordered elements. For example, imagine you are at the beach and collecting seashells into a bag. Each shell is unique and has no fixed place in the bag, making this collection an excellent example of a set. Sets are useful in programming and data processing because they allow you to efficiently manage unique elements and perform operations such as union, intersection, and difference.
The main properties of sets include the following. First, sets are collections of unique elements, which means that each element in the set appears exactly once. Second, the order of the elements in a set does not matter; this means that the set {A, B, C} is equivalent to the set {C, A, B}. In addition, sets can be finite or infinite, depending on the number of elements they contain. Another important property is the ability to perform set operations, such as union, intersection, and difference. These operations allow you to effectively work with and analyze data. Understanding these properties is the foundation for the study of set theory and its applications in various fields, including mathematics, computer science, and statistics.
- Uniqueness: each element of a set is unique. If you try to create a duplicate in the set, Python will not allow it.
- Unordered: elements of a set do not have an ordinal number.
- Mutable: you can add elements to or remove elements from a set.
Sets in Python are unordered collections, which means that you cannot access elements by index, as is possible with tuples and lists. However, one of the main advantages of sets is the high speed of checking the presence of an element. Because the elements in a set have no fixed order, a computer can efficiently process the entire collection at once, significantly speeding up searches. This makes sets an ideal tool for situations where you need to quickly determine whether an element belongs to a group.
Sets are also used to remove duplicates from data. For example, if you have collected a list of duplicate phone numbers from a website, you can convert this list into a set. This will automatically remove all duplicate entries, leaving only unique numbers. This makes sets an effective tool for processing and cleaning data from redundant information.
Skillbox Media provides materials on various collection types in Python, including lists, dictionaries, and tuples. Learning these data structures will help you choose the most appropriate option for your needs. Get familiar with each collection type to deepen your knowledge and improve your Python programming efficiency.
What objects can be added to a set
Sets in Python can only contain immutable objects. This means that elements added to a set cannot be modified after they are created. Immutable objects include data types such as strings, numbers, and tuples. Using mutable objects such as lists or other sets is not allowed and will result in an error. This property ensures the uniqueness of elements in a set and optimizes search, addition, and deletion operations. Proper use of sets allows for efficient data management and improves program performance.
- integers;
- floating-point numbers;
- strings;
- tuples.
The data is stored as a hash, which is a unique bit array, rather than in its original form. This approach makes it easier to find elements in the collection. For this system to work correctly, each element must always return the same value. Data hashing significantly accelerates data retrieval and processing, making it an essential tool in modern data storage systems.
Set objects cannot be data structures such as lists, dictionaries, and other mutable data types that can be overwritten during program execution. This is because sets require unique and immutable elements, which is impossible to achieve with mutable objects. Therefore, only immutable data types, such as tuples or strings, should be chosen for use in sets.

Read more:
Hash Function: Definition, Purpose, and Operating Principle
A hash function is an algorithm that transforms input data of arbitrary length into a fixed set of characters. The primary purpose of hash functions is to create unique identifiers for data, allowing for its efficient storage and processing.
Hash functions are widely used in various fields, such as cryptography, password storage, data integrity verification, and digital signature creation. They help ensure information security and protection, and also speed up data searching and sorting processes.
A hash function operates by calculating a hash value, which is the result of processing the original data. Even a small change in the input information results in a significant change in the hash value, making hash functions useful for detecting counterfeiting and ensuring file integrity.
An important aspect of hash functions is their resistance to collisions, that is, a situation when different input data generates the same hash value. Strong hash functions minimize the likelihood of such collisions, which makes them particularly valuable in the field of information security.
Therefore, hash functions play a key role in modern digital technologies, ensuring the protection of data and its efficient use.
Creating Sets
There are many ways to create objects, and each of them has its own characteristics and advantages. By experimenting with different methods, you can achieve unique results and solutions. The right approach to creating objects allows not only to improve quality but also to optimize processes. It is important to consider your goals and objectives to choose the most appropriate method that will meet your project requirements.
Inside the parentheses, specify the elements to add to the set. Duplicate elements inside the parentheses will not cause an error, but duplicates will not be stored in the collection. This way, the set automatically removes duplicate values, ensuring that each element is unique.
It is important to note that if you do not specify the arguments inside the curly braces, an empty dictionary will be created, not an empty set, as it might seem at first glance. To obtain an empty set, you need to use the set() function. This knowledge is especially useful when working with Python, since the correct use of data types is critical to task execution and code optimization.
The set() function in Python takes a single argument - an iterable object, such as a list, tuple, string, or other iterable object. It returns a set containing the unique elements of that object. If you need to create an empty set, simply call set() without parameters. This is a convenient way to work with unique data and store it efficiently in Python.
Creating sets from a list is an important process in programming and data processing. Sets, as a data structure, allow you to store unique elements and provide quick checking for the presence of values. To convert a list into a set, in most programming languages, it is enough to use built-in functions. For example, in Python, you can use the set() function, which automatically removes duplicates from a list and forms a set. This allows for efficient data management, especially when analyzing large amounts of information. Thus, creating sets from a list not only simplifies working with data but also improves code performance.
Reworking text requires attention to keywords and phrases for search engine optimization. Here is an updated version without unnecessary characters and sections.
Transforming text can be accomplished through structuring and changing the wording. The basic idea remains, but the content becomes more accessible and attractive to the reader. Using keywords and phrases related to the topic will help improve visibility in search engines, which in turn will increase traffic to the site. It's important to preserve the essence of the original text while adding valuable information and simplifying perception. This approach ensures better readability and comprehension, which is an important aspect of successful content.
Each character in a string is represented as an element of a set. Duplicate characters are ignored and not included in the final result.
Creating a set from a tuple is a simple and effective operation in Python. To do this, simply use the built-in set() function, which takes a tuple as an argument and converts it to a set. A set, unlike a tuple, does not allow duplicates and ensures that its elements are unique. This makes sets ideal for operations involving the removal of duplicate values and mathematical operations such as union and intersection.
An example of creating a set from a tuple:
«`python
my_tuple = (1, 2, 2, 3, 4)
my_set = set(my_tuple)
print(my_set)
«`
This code will create a set containing the unique elements of the tuple: {1, 2, 3, 4}. This demonstrates how easy it is to use sets to work with data in Python.
Creating a set from a range in Python is a convenient and efficient way to work with unique values. To do this, use the built-in `range()` function, which generates a sequence of numbers. Using this function, you can create a set by passing the result to the `set` constructor.
For example, to create a set consisting of numbers from 0 to 9, you can use the following code: `my_set = set(range(10))`. This will create a set with elements {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.
Using a set from a range allows you to easily manage unique elements and performs important functions such as checking if an element exists or removing duplicates. Sets in Python provide high performance when performing operations on data, which makes them a popular choice for developers.
Thus, creating a set from a range is a simple and effective method for working with collections of unique values in Python.
To create a set from a numeric value, you must first convert it to a string using the str() function. This will ensure correct conversion and error-free creation of the set.
When creating a set from a dictionary, only the keys will be stored, since the values are not included in the set.
Creating sets in Python can be done quickly and conveniently. To appreciate the benefits of this approach, let's consider the process of creating a set using a generator and a traditional loop. Generators allow you to create sets more concisely and efficiently, simplifying your code and improving its readability. Unlike loops, which require more lines of code and can be less intuitive, generators provide a compact and understandable solution for creating sets. This makes them an ideal tool for developers looking to optimize their code and improve its performance.
Generator syntax is significantly more concise. Using this method improves the readability of your code and reduces the likelihood of errors during further maintenance.
frozenset() is an immutable version of a set, meaning you cannot add or remove elements after it has been created. To create a frozenset, you can use the following syntax:
How to add elements to a set
There are three methods for adding elements: add(), update(), and union(). Each of these methods is designed to perform specific tasks related to data management. The add() method allows you to add individual elements, update() is used to update existing values, and union() is used to combine multiple data sets. Optimal use of these methods ensures efficient data management and modification in your projects.
The add() method is used to add a single object to a set. This method allows you to efficiently expand a set while ensuring the uniqueness of the elements added. When you call the add() method, the object will be added only if it does not already exist in the set. This makes the add() method an indispensable tool for working with data collections where the uniqueness of elements is important.
The update() method is designed to add multiple elements at once. It takes a list, string, or any other iterable object as an argument. This allows you to efficiently update data collections, simplifying the process of adding new elements and improving the performance of working with them.
Python allows you to combine sets using the union() method. Moreover, if two sets contain the same elements, the merged result will leave only one copy of each element in the new set. This allows you to efficiently manage data and eliminate duplicates when working with sets.
Removing Set Elements
Python uses built-in methods to remove elements from a set: remove(), discard(), clear(), and pop(). Let's look at each of them in more detail. The remove() method removes the specified element, but raises an error if the element is not present. The discard() method also removes an element, but does not raise an error if the element is not found. The clear() method clears the set by removing all of its elements. The pop() method removes and returns an arbitrary element from a set, but raises an error if the set is empty. These methods provide different ways to manage the elements of a set in Python, allowing you to work with data efficiently.
The remove() method is used to remove an element from a set. If the specified element is not in the set, the interpreter will throw an exception. This method is important for managing the contents of sets in Python, ensuring that the desired elements are removed accurately. By using the remove() method, developers can work with sets efficiently, ensuring that removal operations are performed correctly.
The discard() method provides a safer execution of operations, since it does not raise an exception if an element is missing. This makes it useful in situations where you need to remove an element, but cannot always guarantee its presence. Using the discard() method avoids potential errors and improves the stability of your code.
The pop() method is used to remove an arbitrary element from a set. This method allows you to manage elements efficiently, providing the ability to remove without having to specify a specific element.
If you need to completely clear a collection, it is recommended to use the clear() method. This method removes all elements from the collection, thereby ensuring that it is completely cleared. By using clear(), you can effectively manage memory and maintain optimal data.
Set Operations
The set data type is designed to perform operations on mathematical sets, including union, intersection, difference, and symmetric difference. Using the set data type allows you to efficiently manage and process collections of unique elements, making it a useful tool in a variety of programming and data analysis tasks.
To combine multiple sets in Python, you can use the union() method or the | operator. These tools allow you to efficiently combine data from different sets, creating a new set that contains all the unique elements. The union() method returns a new set without modifying the original ones, while the | operator also creates a new set, but does so more concisely. Using these methods and operators simplifies working with sets and allows for easy management of data collections in Python.
The result is a new set containing all unique elements from each of the sets under consideration. This allows for efficient data merging and elimination of duplicates, which is especially important when analyzing and processing information. This approach ensures a high degree of uniqueness and integrity of data, which in turn improves the quality of analysis and decision making.

Set intersection in Python can be accomplished in two ways: using The intersection() method and the & operator. Both methods return a new set containing only those elements that are present in both original sets. If there are no common elements, the result is an empty set. These approaches are useful when working with data that requires identifying common values from different sets.
In the example, set1 and set2 contain the common elements 3 and 4, making their intersection result {3, 4}. The intersection of sets helps identify common elements, which is an important operation in set theory and is used in various fields such as mathematics, programming, and data analysis.

To remove non-matching elements from the original set, use the intersection_update() method or the &= operator. These tools allow you to efficiently keep only those elements that are present in both sets. Using these methods helps optimize work with sets in Python and simplifies the process of filtering data.
The difference of sets is a set of elements that are present in the first set but not in the second. In other words, the difference can be thought of as the result of subtracting the second set from the first. This is an important concept in set theory, which helps in the analysis and comparison of different data sets. The difference of sets is used in mathematics, programming, and other fields to solve problems related to data analysis and classification.
To calculate the difference between sets in the Python programming language, use the difference() method and the subtraction operator (-). The difference() method returns a new set containing the elements present in one set but not in the other. The — operator also allows you to efficiently perform this operation, providing a similar result. Using these tools simplifies working with sets and allows you to quickly find unique elements.

To remove duplicates from a set in Python, you can use the method difference_update() or the -= operator. These tools allow you to efficiently remove matching elements and manipulate the contents of a set, ensuring its uniqueness. The difference_update() method modifies the current set by removing elements that are present in another set, while the -= operator also removes elements, making it more concise. Both methods are convenient and powerful for working with sets in Python, allowing you to optimize your code and improve its readability.
The symmetric difference of sets is the set of elements that belong to either the first or the second set, excluding their intersection. This means that the symmetric difference includes all unique elements of both sets, excluding those that are present in both. Understanding the symmetric difference is useful in various fields, such as set theory, statistics, and data analysis, as it allows you to identify differences between sets and analyze the unique characteristics of each.
In Python, you can use the symmetric_difference() method or the ^ operator to calculate the symmetric difference. The symmetric difference of two sets represents the elements that are present in one set but absent from both. This is a useful tool for data analysis and collection processing, allowing you to efficiently find unique values. Using these methods simplifies working with sets and makes the code more readable.
To remove common elements from a set, you can use the method symmetric_difference_update() or use the ^= operator. These tools allow you to efficiently modify a set by excluding elements that are present in both sets. Using these methods helps optimize data handling and improves the performance of set operations in Python.
How to Check for Elements in Sets
You can use the len() and bool() functions to check for elements in a set. The len() function returns the number of elements in the set, allowing you to determine whether it is empty. The bool() function, on the other hand, returns a Boolean value indicating whether the set contains elements. If the set contains at least one element, bool() returns True; otherwise, it returns False. These functions are powerful tools for working with sets in Python.
The len() function is used to determine the length of a set. If the result is 0, it means the collection is empty.
The bool() function returns False for empty sets and True for non-empty sets. It is a useful tool for checking the presence of elements in a set, as it allows you to quickly determine whether it contains data. Using the bool() function helps in managing program logic and simplifies conditional tests.
Comparing Sets
Sets are compared using the equality (==) and inequality (!=) operators. The == operator checks whether two sets have common elements, while the != operator is used to determine the differences between them. These operators allow you to efficiently evaluate whether sets contain the same objects or have elements that are different.
Comparison operators such as >, >=, <, <= are also used to analyze sets. We'll explore these operators in more detail later in the context of subsets and supersets.
How to Check if an Element is in a Set
In Python, the in operator is used to check if an element is in a collection. This operator returns True if the element is found in the collection and False if it is not. Using the in operator allows you to efficiently search through various collection types, such as lists, tuples, sets, and strings. This makes it an indispensable tool for working with data in Python.
The not in operator can be used to check if an object is not part of a set. This allows you to effectively filter data and avoid unnecessary elements in various collection operations. Using this operator improves code readability and simplifies data processing logic.
How to Check if One Set is a Subset of Another
Python provides tools for working with sets, such as the issubset() method and comparison operators: >, >=, < and <=. These tools allow you to conveniently check relationships between sets, including their subsets and size comparisons. Using the issubset() method, you can determine whether one set is a subset of another, which is useful for data analysis and performing various logical operations. Comparison operators provide a way to quickly and easily evaluate which set is larger or smaller, which can also be useful in various algorithms and information processing.
The issubset() method determines whether one set is a subset of another. It returns True if all elements of the first set are contained in the second set, and False otherwise. This method is useful for checking relationships between sets and can be applied to a variety of tasks related to data analysis and collection processing. Using issubset() allows you to easily establish membership of elements in sets and optimize algorithms for working with them.
In this example, set1 is a subset of set2, since all the elements of set1 are in set2. However, set1 is not considered a subset of set4, since set1 has a unique element that is not in set4. This demonstrates important aspects of set theory, where a subset is defined by the presence of all of its elements in another set.
If two sets are equal, the issubset() method will return True. This means that every value from one set is present in the other. Using the issubset() method allows you to effectively check the relationship between sets in Python.
An alternative method for checking subsets is to use the < (less than) and <= (less than or equal) operators. These operators allow you to determine whether one set is a subset of another. If the sets are identical, the < operator returns False, while the <= operator returns True. This makes these operators useful for analyzing relationships between sets in programming and mathematics.
To test whether one set is a superset of another, use the >= (greater than or equal to) and > (greater than) operators. If two sets are identical, the > operator returns False, while the >= operator returns True. This allows you to efficiently determine relationships between sets and evaluate their hierarchy.
What to remember
Let's summarize the main points of the article.
- A set in Python is a mutable data structure that contains unique and unordered elements. Sets are useful when you need to quickly check for the presence of an element or remove duplicates from large sets of data.
- Sets in Python can only contain immutable data types—integers, strings, and tuples. Dictionaries, lists, and other mutable objects cannot be part of a set.
- Since set elements are unordered, you cannot access them by index—like elements in lists and tuples.
- The set data type supports mathematical operations on sets (e.g., union, intersection, difference).
Learn more about programming and coding in our Telegram channel. Join us and receive relevant news, useful tips, and interesting materials!
Rework the text, maintaining the main topic and avoiding unnecessary additions. Optimize it for SEO and, if necessary, supplement the content. Avoid using emojis and unnecessary symbols, and don't include numbered or bulleted lists. Use plain text only.
Read also:
- Lists in Python: What They Are and How to Work with Them
- "The Main Thing Is Not the Offer, but the Enjoyment of What You Do": The Path of a Beginner Python Developer
- What Are Tuples in Python and How to Use Them

