Sets in Python

Sets

 

We all have learnt about sets and set theory in mathematics at some point. The mathematical definition of a set can be abstract and difficult to grasp.

In simple words, a set is a well-defined collection of distinct objects, typically called elements or members.

Sets in Python

Python Sets

In Python set is a built-in type having characteristics:

  • Sets is an unordered collection of items.
  • Elements in set are unique ( No Duplicate elements ).
  • Elements of set are immutable ( Can not be changed ), however a set itself is mutable. We can add or remove items.

Creating Python Sets

A set can be created in two ways :

  1. Placing elements inside { } braces separated by comma
  2.  By using built-in set() function

#Creating python sets

#create a set usign {}
#Set having same type of elements
#output: {1, 2, 3, 4}
mySet={1,2,3,4}
print(mySet)

#Set having different types of elements
#output: {‘hello’, ‘prepinsta’, 2, 1}
mySet={“prepinsta”,1,2,2,“hello”}
print(mySet)

#create set using set(argument) method
#By passing a string as an argument
#output: {‘A’,’P’,’R’,’T’,’N’,’I’,’E’,’S’}
mySet=set(“PREPINSTA”)
print(mySet)

#By passing a variable as an argument
#output: {‘a’, ‘n’, ‘u’, ‘M’, ‘s’, ‘k’}
s=“Muskan”
mySet=set(s)
print(mySet)

#By passing a list as an argument
#output: {1, 2, 3, 4, 5}
mySet=set([1,2,3,4,5])
print(mySet)


Output :

{1, 2, 3, 4}

{'hello', 'prepinsta', 2, 1}

{'A', 'P', 'R', 'T', 'N', 'I', 'E', 'S'}

{'a', 'n', 'u', 'M', 's', 'k'}

{1, 2, 3, 4, 5}

A set can be empty also, but creating an empty set is a bit tricky.

Python interprets empty curly braces ( { } ) as an empty dictionary, so their is only one way to define an empty set.

Using set() function we can create an empty set.



#creating an empty set
mySet=set()
print(mySet)


Output: 

set()

Modifying Python Sets

We can modify python sets by inserting and deleting elements from set.

Inserting elements into Python Sets

We can insert elements into python sets by two methods:

  1. add() – Single element can be inserted
  2. update() – Multiple elements can be inserted

#create set
#output : {1, 2.0, ‘hello’, ‘M’, ‘Hello’}
mySet = { “Hello” , ‘M’ , 1 , 2.0 , 1 , “Hello” , “hello” }
print(mySet)

#insert single element using add()
#”PrepInsta” will be added to the set
#output : {1, 2.0, ‘hello’, ‘M’, ‘Hello’, ‘PrepInsta’}
mySet.add(“PrepInsta”)
print(mySet)

#insert multiple elements using update()
#letters of “prepinsta” word will be added to the set
#output : {‘a’, 1, 2.0, ‘n’, ‘t’, ‘e’, ‘hello’, ‘P’, ‘M’, ‘I’, ‘Hello’, ‘s’, ‘r’, ‘p’, ‘PrepInsta’}
mySet.update(“PrepInsta”)
print(mySet)

#inserting the element which is already present in the set
#set will remain same
#output : {‘a’, 1, 2.0, ‘n’, ‘t’, ‘e’, ‘hello’, ‘P’, ‘M’, ‘I’, ‘Hello’, ‘s’, ‘r’, ‘p’, ‘PrepInsta’}
mySet.add( 1 )
print(mySet)


Output :

{1, 2.0, 'hello', 'M', 'Hello'}

{1, 2.0, 'hello', 'M', 'Hello', 'PrepInsta'}

{'a', 1, 2.0, 'n', 't', 'e', 'hello', 'P', 'M', 'I', 'Hello', 's', 'r', 'p', 'PrepInsta'}

{'a', 1, 2.0, 'n', 't', 'e', 'hello', 'P', 'M', 'I', 'Hello', 's', 'r', 'p', 'PrepInsta'}

Deleting elements from Python Sets

Deletion can be done by three methods :

  1. remove() – Removes the element from the set only if the element is present in the set otherwise error or exception is raised.
  2. discard() – Removes the element from the set only if the element is present in the set otherwise no error or exception is raised and the original set is printed.
  3. pop() – Randomly removes an item from the set and return removed item.

#create set
#output : {1, 2.0, ‘hello’, ‘M’, ‘Hello’}
mySet = { “Hello” , ‘M’ , 1 , 2.0 , 1 , “Hello” , “hello” }
print(mySet)


#delete element using remove() which is present in the set
#output : {1, 2.0, ‘M’, ‘Hello’}
mySet.remove(“hello”)
print(mySet)


#delete element using discard() which is present in the set
#output : {2.0, ‘M’, ‘Hello’}
mySet.discard(1)
print(mySet)


#delete element using pop()
#output : {‘M’, ‘Hello’}
mySet.pop()
print(mySet)


Output :

{1, 2.0, 'M', 'Hello', 'hello'}

{1, 2.0, 'M', 'Hello'}

{2.0, 'M', 'Hello'}

{'M', 'Hello'}

Difference between remove() and discard() methods
remove()

#delete element using remove() which is not present in the set
#output : KeyError: ‘PrepInsta’
mySet.remove(“PrepInsta”)
print(mySet)


Output :
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
 in ()
     50 #output : KeyError: 'PrepInsta'
---> 51 mySet.remove("PrepInsta")
     52 print(mySet)

KeyError: 'PrepInsta'

discard()

#delete element using discard() which is not present in the set
#output : {‘M’, ‘Hello’}
mySet.discard(“PrepInsta”)
print(mySet)


Output :

{'M', 'Hello'}

If we try to pop() element from an empty set an error will occur.


#trying to pop from an empty set
#output : KeyError: ‘pop from an empty set’                               
emptySet = set()
emptySet.pop()
print(emptySet)


Output :
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
 in ()
     61 emptySet = set()
---> 62 emptySet.pop()
     63 print(emptySet)

KeyError: 'pop from an empty set'

Iterators in Python Sets

There is no index attached to any element in a python set. So they do not support any indexing or slicing operation. We can iterate python sets


mySet = { “Hello” , ‘M’ , 1 , 2.0 , “hello” }

for i in mySet:
    print(i)
 
Output :

1
2.0
M
Hello
hello

Membership Test


#create a set
mySet = { 1,5,10,15,20,25 }

for i in range(1,16):
    #checking the membership of i in mySet
    if i in mySet:
        print(i)


Output : 

1
5
10
15