Sets in Python

Sets in Python

Play this article

What are Sets in Python?

Sets are collections of unique elements, which means an element is present only once in a set.

They are defined using the curly bracket syntax: my_set={elements}

We can add a new element to the set. but, we can't add an existing element to the set.

union()

This method creates a new set with all elements in both sets and removes the duplicate elements. In mathematics, we know A∪B(A union B) is the same procedure. syntax:1st_set.union(2nd_set)

Example

my_set1={1,2,5,0}
my_set2={1,2,3,4}
all_elements=my_set1.union(my_set2)
print(all_elements)
#{0, 1, 2, 3, 4, 5}

intersection()

This method creates a new set with only those elements which are present in both sets. syntax:1_set.intersection(2nd_set)

Example

x = {"python", "git", "django"}
y = {"numpy", "flask", "python"}
z = x.intersection(y)
print(z)
#python

difference()

This method removes the common elements and gives the remaining elements as output. syntax:1st_set.difference(2nd_set)

Example

x = {"python", "git", "django"}
y = {"numpy", "flask", "python"}
z = x.difference(y) 
print(z)
#{'django', 'git'}

discard()

This method removes the specified element from the set. syntax:variable_set.discard(element)

Example

x = {"python", "git", "django"}
x.discard("git")
print(x)
#{'python', 'django'}

copy()

This method returns the copy of the specified set. syntax: existing_set.copy()

Example

x = {"python", "git", "django"}
y= x.copy()
print(y)
#{'python', 'git', 'django'}

Converting a list to a set

A list can be converted to a set using a built-in (set) function

Example

my_list=[1,2,3,4,1,2,3,4]
my_set=set{my_set}              
print(my_set)
#{1,2,3,4}

Note: A set can be converted into the list using a built-in (list) function

Did you find this article valuable?

Support Prahlad Inala by becoming a sponsor. Any amount is appreciated!