Python Sets
Set
Multiple items are being stored in a single variable using sets.
A set is an unsorted and unindexed collection of items.
Curly brackets {}
are used to write sets.
Example :- Create a Set :
myset = {"html", "css", "java"}
print(myset)
# Note: the set list is unordered, meaning: the items will appear in a random order.
# Refresh this page to see the change in the result.
Output :-
Note : Sets are not arranged, so you can't be sure the items are shown in which order.
Note : If you run the program multiple times, you can see different result.
Set Items
Unordered unchangeable items are specified and Duplicate values are not permitted.
Unordered
Unordered means that the items in a set have no specific order.
Set items can be displayed by index or key in a different order each time you use them.
Unchangeable
Sets cannot be modified, which means that after the set is created, we cannot change items.
You cannot modify the existing items once a set is created, but new items can also be added.
Duplicates Not Allowed
Sets can't possess the same value for two items. Duplicate values are ignored by sets.
Example :- A simple set with duplicate values :
myset = {"html", "css", "java", "html"}
print(myset)
Output :-
Get the Length of a Set
Use the len()
method to figure out how many objects has set.
Example :- Get the number of items in a set :
myset = {"html", "css", "java"}
print(len(myset))
Output :-
Related Links
Set Items - Data Types
Any data type can be used to set items :
Example 1 :- Creating multiple sets with various types like string, int and boolean :
set1 = {"html", "css", "java"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False}
print(set1)
print(set2)
print(set3)
Output :-
{1, 3, 5, 7, 9}
{False, True}
Various data types can be found in a set:
Example 2 :- A single set with different datatypes like strings, integers and boolean values :
set1 = {111, "abc", 4.2, True}
print(set1)
Output :-
type()
Sets are objects with the data type 'set' in Python :
Example :- What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
Output :-
The set() Constructor
The set()
constructor can also be used to create a set.
Example :- Using the set()
constructor to make a set :
myset = set(("a", "b", "c"))
print(myset)
# Note: the set list is unordered, so the result will display the items in a random order.
Output :-
Python - Access Set Items
Python provides readonly access to an set.
Access Items
An index or a key can't be used to access the elements in a set.
The in
keyword allows you to ask if a specific value is present in a set by looping through the items in the set using the for
loop.
Example 1 :- Print all values from a set using for
loop :
myset = {"html", "css", "java"}
for x in myset:
print(x)
Output :-
css
java
Example 2 :- Check to see if the word "java" is in the set :
myset = {"html", "css", "java"}
print("java" in myset)
Output :-
Change Items
The items in a set can't be changed once it's been formed, but you can add new items.
Related Links
Python - Add Set Items
The items in a set can't be changed once it's been formed, but you can add new items.
Add New Items
Use the add()
method to add one item to a set :
Example :- Add a new item to set:
myset = {"html", "css", "java"}
myset.add("python")
print(myset)
Output :-
Add Sets
Using the update()
method, you can add items from another set to the current set.
Example :- Add elements from myset2
into myset
:
myset = {"html", "css", "java"}
myset2 = {"jquery", "nodejs"}
myset.update(myset2)
print(myset)
Output :-
Add Any Iterable
When using the update()
method, the object in question doesn't have to be a set, but rather, any iterable object (tuples, lists, dictionaries etc.).
Example :- Add a list to set
myset = {"html", "css", "java"}
mylist = ["c", "cpp"]
myset.update(mylist)
print(myset)
Output :-
Python - Remove Set Items
Use the remove()
or discard()
methods to remove an item from a set.
The remove()
method will throws an error, if the item not found.
The discard()
method will not raise any error, if the item not found.
Example 1 :- Using the remove()
method, remove "java" from the set :
myset = {"html", "css", "java"}
myset.remove("java")
print(myset)
Output :-
Note :- The remove()
function throws an error if the item doesn't exist.
Example 2 :- Use the discard()
function to remove "css" :
myset = {"html", "css", "java"}
myset.discard("css")
print(myset)
Output :-
Note : If the object to be removed doesn't exist, discard()
will not raise an error.
The pop()
method can also be used to delete an item, however it will
only remove the final item. Recall that sets are unordered, thus you won't be able to tell which item
has been deleted.
The removed item is returned as a result of the pop()
method's return value.
Example 3 :- The pop()
method can be used to remove the last item :
myset = {"html", "css", "java"}
x = myset.pop()
print(x) #removed item
print(myset) #the set after removal
Output :-
{'html', 'java'}
Note : If you use the pop()
method, you won't know which item has been removed because sets are unordered.
Example 4 :- Using the clear()
method, the set is emptied of its contents :
myset = {"html", "css", "java"}
myset.clear()
print(myset)
Output :-
Example 5 :- With the del
keyword, the entire set will be removed :
myset = {"html", "css", "java"}
del myset
print(myset) #this will raise an error because the set no longer exists
Output :-
File "demo_set_del.py", line 5, in < module>
print(myset) #this will raise an error because the set no longer exists
NameError: name 'myset' is not defined
Python - Loop Sets
Using a for
loop, you may loop through the set elements :
Example :- Using a for
loop, print out the values in the set :
myset = {"html", "css", "java"}
for x in myset:
print(x)
Output :-
css
java
Python - Join Sets
Two or more sets can be joined in a variety of ways in Python.
Join Two Sets
You can use the union()
method, which returns a new set containing all items from both sets, or the update()
method, which updates all items from one set into another :
Example 1 :- All elements from both sets are returned by the union()
method :
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
Output :-
Example 2 :- As a result of calling update()
, the items from Set2 are inserted into Set1 :
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Output :-
Note :- It's important to note that both union()
and update()
will remove any duplicates.
Keep ONLY the Duplicates
By default, only the items that appear in both sets are kept by intersection_update()
.
Example 1 :- Retain the items that appear in both x
and y
sets :
x = {"a", "b", "c"}
y = {"a", "c", "d"}
x.intersection_update(y)
print(x)
Output :-
Using the intersection()
technique, you'll get a new set containing only the elements that are in both sets.
Example 2 :- Return a set that contains the items that exist in both set x
, and set y
:
x = {"a", "b", "c"}
y = {"a", "c", "d"}
z = x.intersection(y)
print(z)
Output :-
Keep All, But NOT the Duplicates
When using the symmetric_difference_update()
technique, only the elements that NOT present in both sets will be kept.
Example 1 :- Keep the items that are not present in both sets :
x = {"a", "b", "c"}
y = {"a", "c", "d"}
x.symmetric_difference_update(y)
print(x)
Output :-
With this procedure, you will get a new set that only contains the components that are NOT present in both sets.
Example 2 :- You'll get back a set that has all things from both sets, excluding those that are in both sets :
x = {"a", "b", "c"}
y = {"a", "c", "d"}
z = x.symmetric_difference(y)
print(z)
Output :-