In this article, we will discuss on the python sets with proper explanations and examples. The following is the contents of this article.
- Introduction
- Access item
- Check item
- Length of a set
- Add item
- remove item
- Join two sets
- Set constructor
- Set method
Introduction
A collection of unordered and unindexed items is called a set. It represented by a curly braces “{ }”
set1 = {"apple", "banana", "orange"}
print(set1)
Access Items
Since sets are unordered so we can’t access an item using its index. Because any item can be accessed by any index. But we can use a loop through the sets just like as we did it in the tuple.
set1 = {"rose", "sunflower", "jasmine", "tulip"}
for i in set1:
print(set1)
#returns
" " " rose
sunflower
jasmine
tulip " " "
Check Item
set1 = {"apple", "banana", "orange"}
print( "cherry" in set1)
#returns False
Get the Length of a Set
To get the length of a set we use len() method.
set1 = {"apple", "banana", "orange"}
print(len(set1)) #returns 3
Add Item to the set
If we want to add single item we can use add() method but if we want to add more than one item we can use update() method.
set1 = {"apple", "banana", "orange"}
set1.add("grapes")
print(set1)
set1 = {"apple", "banana", "orange"}
set1.update(["grapes", "cherry", "mango"])
print(set1)
Remove Item from Set
There are several methods to remove item from a set. We use remove() method in the next statements.
set1 = {"apple", "banana", "orange"}
set1.remove("banana")
print(set1)
set1 = {"apple", "banana", "orange"}
set1.discard("banana")
print(set1)
The main difference between remove() and discard() is that if the item to be removed does not exits it will not show any error. But for the same case remove() doesn’t show an error.
clear() and del() both delete the set entirely.
set1 = {"apple", "banana", "orange"}
dell set1
print(set1)
set1 = {"apple", "banana", "orange"}
set1.clear()
print(set1)
Join Two Sets
There are several ways to join two or more sets in Python. To know more about this you can refer to this site.
You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:
set1 ={"Jupyter", "spyder", "PyCharm"}
set2 = { 1, 2, 3}
set3= set1.union(set2)
print(set3)
This is same for the update() method also. They both exclude duplicity in the set.
The set() Constructor
We use double rounded brackets to introduce set() constructor in Python. Basically we can create or better to say construct a set.
set1 = set(("apple", "banana", "grapes"))
print(set1)
Set Methods
Python has a number of built-in set methods. Those are :
- add()
- clear()
- difference()
- discard()
- intersection()
- isdisjoint()
- update()
- intersection_update()
- copy()
- union
Above methods are discussed here.