- Getting Started with Python Sets and Python Set Operations
- What Are Sets in Python?
- Create a Python Set
- Python — Access Set Items
- Example
- Example
- Change Items
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- How to access elements in a Set
- Python Sets
- Access Elements of a Set
- Example: Accessing Using a loop and in operator
- Example: Accessing Using in Operator
- Example: Accessing Using iter and next keyword
- Conclusion
Getting Started with Python Sets and Python Set Operations
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Pythons sets are unordered collections modeled on mathematical sets, in which elements are unique. Python sets support the logical operations of mathematical sets, like union, intersection, and difference. This example code declares a new set and adds the elements of a second set to it, showing that the updated set contains unique elements:
- What Python sets are and what kinds of elements they can contain
- How to fetch an element from a Python set, check if an element exists in a set, and iterate through the elements of a set.
- How to create a Python set with set literals, the set() constructor function, and the set comprehension syntax.
- How to add elements to and remove elements from Python sets
- How to combine sets with the union, intersection, difference, and symmetric difference Python set operations.
- How to compare Python sets with the subset, superset, and disjoint relationships.
What Are Sets in Python?
In Python, a set is an unordered, mutable collection of unique elements. Mathematical set operations like union, intersection, and difference can be performed on them. Two different sets can be compared with the subset, superset, and disjoint relations.
This example set uses the set literal syntax and contains the even integers between 2 and 8:
Sets can contain elements of different types. This set contains some integers and some strings:
The members of a set must be hashable. Hashable objects are generally immutable. Hashable objects must implement the __eq__() method, so two different hashable objects and can be compared to check if they are equal in value to each other. For example, two string objects can be compared to check if they are the same string.
Technically, a hashable object’s __hash__() function must always return the same value for the lifetime of the object, rather than the object itself being immutable. This blog post describes why, in practice, hashable objects used with sets are also immutable.
Integers and strings are built-in Python types that are hashable and can be stored in a set. Mutable container types like lists, dictionaries, and sets are not hashable, because their contents can change. A Python tuple is hashable if each of its values is hashable.
Create a Python Set
Python provides a few ways to create sets:
- A Python set can be declared with the set literal syntax. A set literal consists of a comma-separated list of unique, hashable objects wrapped in curly braces.
Python — Access Set Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
Example
Loop through the set, and print the values:
Example
Check if «banana» is present in the set:
Change Items
Once a set is created, you cannot change its items, but you can add new items.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
How to access elements in a Set
In this article, we will learn to access elements in a set in Python. We will use some built-in functions, some simple approaches, and some custom codes as well to better understand the topic. Let’s first have a quick look over what is a set in Python.
Python Sets
Python Set is a built-in data type. It is a collection of unordered data values. An unordered dataset leads to unindexed values. Set values cannot be accessed using index numbers as we did in the list. Set values are immutable which means we cannot alter the values after their creation. Data inside the set can be of any type say, integer, string, or float value. For example,
Access Elements of a Set
Reading elements of a set in Python basically means accessing one or multiple elements of the set. We know that set values are unordered which means the user is not sure of the order in which data values appear. Therefore, it is unindexed. We cannot access the elements of a set using an index say, set[0] . It will not print the 0th index value, instead, it will return an error. In this article, we will learn to access one or more elements and observe the following outputs.
Let us look at the below examples and learn what are the different ways to read elements of a given set.
Example: Accessing Using a loop and in operator
This example uses a loop to iterate over the elements of a set and checks for elements using in operator. As the set does not have indexes, we can access elements using a loop and perform operations over it.
#input set set1 = #Access element using for loop print("\nReading elements of the set: ") for x in set1: print(x)
Reading elements of the set:
3
4
5
6
11
12
Example: Accessing Using in Operator
To check for a specified value in a set, we can use the in operator. It will return True if that value is in the set else it will return False.
#input set set1 = #check for an element print("apple" in set1) print("watermelon" in set1)
Example: Accessing Using iter and next keyword
This method uses iter to create an iterator object and with the help of next() , it prints the first item of the given input set.
#input set set1 = x = next(iter(set1)) #prints first item print(x)
Note: Generally, the set is converted to a list using the list keyword list(set), and then the reading of set items takes place.
Conclusion
In this article, we learned to read elements of a set by using a loop, in operator, and keywords like next and iter . We used some custom codes as well. We learned that set is an unindexed data type and does not access elements using the index.