In this article, we will learn how to create, modify and access an element of a Python set. While Python Sets have some similarity to Python list, but they have distinct use cases. Sets don’t allow duplicate value unlike Lists.
1. Create Python Set
You can create a set in Python using curly braces {}
or the set()
constructor:
Let’s create a set from an existing list using set ( ) constructor:
Let’s check the type of the set we just created:
2. Access Set Elements
If you try to access Set Elements using index , you will see error – set object is not subscriptable. A set is just an unordered collection of unique elements. So, an element is either in a set or it isn’t. This means that no element in a set has an index.
If you still have to access an element in a set , You can convert the set into a List and apply indexing and slicing as applicable for Python List . Below you can see the same in action :
3. Updating Python Set
Sets are mutable that is we can update it . To add elements to a set, you can use the add()
method. You can see below when we try to add 40 , it added after 20 and before 43 means It’s ordered.
Let’s try to add 40 again and see what’s happens. You will see it will not give an error but also not add another 40 in the set means set doesn’t hold duplicate.
To remove elements, you can use the remove()
method or discard()
method. The key difference is that remove()
raises an error if the element is not found, while discard()
does not:
More Resources:
Want to Learn Python from our Expert . Check this out .
Don’t trust us , See if you like learnpython.com