Python Sets: Functions, Operations, and Examples
What are Sets in Python?
Sets allow you to store several items in a single variable.
Set is one of the four built-in Python data types for storing collections of data. The other three are List, Tuple, and Dictionary, all of which have various properties and applications.
A set is an unsorted, unchangeable, and unindexed collection.
How to Create Python Sets?
The built-in set()
function can be used to create a set by enclosing all of the items in curly brackets & separating them with a comma.
It can include unlimited elements of various categories (integer, float, tuple, string, etc.). A set, on the other hand, can’t include changeable items such as lists, sets, or dictionaries.
myset = {1, 2, 3}
print(myset)
myset = {1, "Hello", (1, 2, 3)}
print(myset)
Output:
How to Modify a set in Python?
The set()
method can be used to create a set by enclosing all of the items in curly brackets and using comma to separate them.
It can include any number of objects of various categories (integer, float, tuple, string, etc.). However, changeable components like lists, sets, and dictionaries are not allowed to be part of a set.
myset = {1,2}
print(myset)
# myset[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
myset.add(3)
print(myset)
# add multiple elements
# Output: {1, 2, 3, 4}
myset.update([2, 3, 4])
print(myset)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
myset.update([4, 5], {1, 6, 8})
print(myset)
Output:
How to Remove Elements From a Python Set?
The methods discard()
& remove()
can be utilized to discard a specific item from a set()
.The only difference is that if the element is not present in the set, the discard()
method leaves the set unmodified. The delete()
function will throw an error in this case (if the element is not present in the set).This is demonstrated in the following example.
# Difference between discard() and remove()
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
Output: