Python Sets
A Set is a collection of items. Sets are unordered that means you cannot be sure how the order of a set will be appeared. Set items also cannot be changed. Sets are used with curly brackets. For example:
set1 = {"c", "python", "java", "javascript"}
Accessing Set Items
You cannot access the set items by referring to the index number. As it is unordered it has no index. you can use a for loop to access the items.
Example:
set1 = {"c", "python", "java", "javascript"}
for x in set1:
print(x)
Output:
c java javascript python
Adding Items
You cannot change an item in a set but you can add new items using the add() method.
Example:
set1 = {"c", "python", "java", "javascript"}
set1.add("c++")
print(set1)
Output:
{'c++', 'java', 'c', 'javascript', 'python'}
If you want to add more than one item to a set you should use the update() method.
Example:
set1 = {"c", "python", "javascript"}
set1.update(["c++", "java", "PHP"])
print(set1)
Output:
{'python', 'java', 'PHP', 'c++', 'javascript', 'c'}
Removing Items
You can remove a specified item by using remove() or discard() method. Difference between these two methods that if the item you want to remove does not exist then the remove() method will raise an error but the discard() method does not.
Example:
set1 = {"c", "python", "java", "javascript"}
set1.remove("javascript")
print(set1)
Output:
{'python', 'java', 'c'}
You can also use the clear() method, which empties the set.
Example:
set1 = {"c", "python", "java", "javascript"}
set1.clear()
print(set1)
Output:
set()
The del statement will delete the set completely.
Example:
set1 = {"c", "python", "java", "javascript"}
del set1
print(set1)
Output:
Traceback (most recent call last): File "C:\Users\Hp\Desktop\py\python.py", line 3, in <module> print(set1) NameError: name 'set1' is not defined
Note: Since the total set is deleted an error is raised in the output.
Length of a Set
You can define the length of a set using the len() method.
Example:
set1 = {"c", "python", "java", "javascript"}
print(len(set1))
Output:
4
Set Methods
There are a set of built-in methods in python which you can use on sets.
Method | Description |
---|---|
add() | Inserts a item to the set |
clear() | Removes all the values from the set |
copy() | Returns a copy of the set |
difference() | Returns a set which contains the diiference between multiple sets |
extend() | Adds the items of a list with the current list |
discard() | Deletes the specified item from a set |
intersection() | Returns a set which is the intersection of sets |
pop() | Removes a value at any position from the set |
remove() | Removes the specified value from the set |
union() | Returns a set which contains the union of sets |
update() | Update the current set with the union of the sets |