Session1 4 (Sets)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

5/6/22, 9:54 AM Session1_4 (Sets)

Another data type in Python is sets. It is a type that could store an unordered collection with no
duplicate elements

It is defined by using a pair of braces { }, and its elements are separated by commas

In [3]:
{3, 3, 2, 3, 1, 4, 5, 6, 4, 2}

{1, 2, 3, 4, 5, 6}
Out[3]:

In [4]:
# Find the unique elements in list [1, 2, 2, 3, 2, 1, 2]
set_1 = set([1, 2, 2, 3, 2, 1, 2])
set_1

{1, 2, 3}
Out[4]:

In [6]:
#Find the unique elements in tuple (2, 4, 6, 5,2)
set_2 = set((2, 4, 6, 5, 2))
set_2

{2, 4, 5, 6}
Out[6]:

In [8]:
#Find the unique character in string “Banana”.
set('Banana')

{'B', 'a', 'n'}


Out[8]:

In [9]:
#Get the union of set_1 and set_2.
print(set_1)
print(set_2)

{1, 2, 3}
{2, 4, 5, 6}

In [10]:
set_1.union(set_2)

{1, 2, 3, 4, 5, 6}
Out[10]:

In [11]:
set_1.intersection(set_2)

{2}
Out[11]:

In [12]:
set_1.issubset({1, 2, 3, 3, 4, 5})

True
Out[12]:

In [ ]:

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session1_4 (Sets).html 1/1

You might also like