Exploring New Techs!

Python - Sets

 



Hello Technotizers, in this article we will be focusing on another Python specific data type which is Sets. Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are SetTuple, and Dictionary, all with different qualities and usage. A set is a collection which is both unordered and unindexed.

Sets are created using curly brackets:

my_set = {'Mumbai','Delhi','Chennai','Kolkata'}
print
(my_set)                                  

The output is obtained as:

{'Kolkata', 'Delhi', 'Chennai', 'Mumbai'}

Some points to be remembered:

·         Set items are unordered, unchangeable and do not allow duplicate values.

·         Set items are not indexed.

·         A set item can be of any data type like int, string or Boolean. A set can also contain items of mixed data types.

 

Examples:

All the below given sets are valid in Python.

set2 = {1, 4, 24, 14, 8}            
set3 = {True, False, False}         
set4 = {"abc", 34, True, 40, "male"}

·         The set() constructor:

It is another way of creating a set.

my_set = set(('Mumbai','Delhi','Chennai','Kolkata'))

So now let’s move forward!! 

·         Accessing set elements:

Set elements cannot be accessed using index, but they have to be accessed using for loop or ask if a specified value is present in a set, by using the in keyword.

city = {'Mumbai','Delhi','Chennai','Kolkata'}
for i in city:                               
    print(i,end=" ")                         
print('Delhi' in
city)                       

The output is obtained as:

Kolkata Delhi Chennai Mumbai
True                        

 

·         Adding set elements:

Once a set is created, the items cannot be changed but new items can be added. To add an item to the set, add() method is used.

city = {'Mumbai','Delhi','Chennai','Kolkata'}
city.add('Surat')                            
print(city)                                  
#to store the item permanently in the set    
city = city.add('Surat')                     

The output is obtained as:

{'Chennai', 'Kolkata', 'Mumbai', 'Delhi', 'Surat'} 

To add items from another set into the current set, use the update() method.

city1 = {'Mumbai','Delhi','Chennai','Kolkata'}
city2 = {'Surat','Indore','Nagpur'}           
city1.update(city2)                           
print(city1)                                  

The output is obtained as:

{'Indore', 'Chennai', 'Nagpur', 'Kolkata', 'Mumbai', 'Delhi', 'Surat'}    

The update() method does not have to append only sets, you can add any iterable object (tuples, sets, dictionaries etc.).

 

·         Remove set items:

The remove() or discard() methods removes a specific item. If the item to remove does not exist, remove() will raise an error. If the item to remove does not exist, discard() will NOT raise an error.

city = {'Mumbai','Delhi','Chennai','Kolkata'}
city.remove('Delhi')                         
print(city)                                  
city.discard('Mumbai')                       
print(city)                                  

The output is obtained as:

{'Kolkata', 'Chennai', 'Mumbai'}
{'Kolkata', 'Chennai'}          

You can also use the pop() method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed. The return value of the pop() method is the removed item.

city = {'Mumbai','Delhi','Chennai','Kolkata'}
x=city.pop()                                 
print(x)                                     
print(city)                                  

The output is obtained as:

Kolkata                       
{'Delhi', 'Chennai', 'Mumbai'}

The ‘del’ keyword entirely deletes the set.

city = {'Mumbai','Delhi','Chennai','Kolkata'}
del city                                     
print(city)                                  

#this will raise an error because the set no longer exists

The clear() method clears the set. The set still exists but without any content.

city = {'Mumbai','Delhi','Chennai','Kolkata'}
city.clear()                                 
print(city)                                  

The output is obtained as:

set()

The output shows that the set is now empty.

 

·         Looping a set:

A for loop is used to loop through a set.

city = {'Mumbai','Delhi','Chennai','Kolkata'}
for i in city:                               
    print(i,end=" "
)                         

The output is obtained as:

Kolkata Delhi Chennai Mumbai

To know more about for loops, refer the article Python-Loops

 

·         Join Sets:

There are several ways to join two or more sets in Python. You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another.

city = {'Mumbai','Delhi','Chennai','Kolkata'}
numbers = {12,98,5,7,25}                     
new_set = city.union(numbers)                
print(new_set)                               

The output is obtained as:

{98, 'Chennai', 5, 7, 12, 'Kolkata', 25, 'Mumbai', 'Delhi'}

Note: Both union() and update() will exclude any duplicate items.

The intersection_update() method will keep only the items that are present in both sets.

city1 = {'Mumbai','Delhi','Chennai','Kolkata'}
city2 = {'Surat','Mumbai','Chennai'}          
city1.intersection_update(city2)              
print(city1)                                  

The output is obtained as:

{'Chennai', 'Mumbai'}

The intersection() method will return a new set, that only contains the items that are present in both sets.

city1 = {'Mumbai','Delhi','Chennai','Kolkata'}
city2 = {'Surat','Mumbai','Chennai'}          
city3 = city1.intersection(city2)             
print(city3)                                  

The output is obtained as:

{'Chennai', 'Mumbai'}

The symmetric_difference_update() method will keep only the elements that are NOT present in both sets. And the symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets.

city1 = {'Mumbai','Delhi','Chennai','Kolkata'}
city2 = {'Surat','Mumbai','Chennai'}          
city1.symmetric_difference_update(city2)      
print(city1)                                  
city1 = {'Mumbai','Delhi','Chennai','Kolkata'}
city2 = {'Surat','Mumbai','Chennai'}          
city3 = city1.symmetric_difference(city2)     
print(city3)                                  

The output is obtained as:

{'Kolkata', 'Delhi', 'Surat'}
{'Kolkata', 'Delhi', 'Surat'}

 

·         Set methods:

Python offers a bunch of set methods given below:

Method

Description

add()

Adds an element to the set

clear()

Removes all the elements from the set

copy()

Returns a copy of the set

difference()

Returns a set containing the difference between two or more sets

difference_update()

Removes the items in this set that are also included in another, specified set

discard()

Remove the specified item

intersection()

Returns a set, that is the intersection of two other sets

intersection_update()

Removes the items in this set that are not present in other, specified set(s)

isdisjoint()

Returns whether two sets have a intersection or not

issubset()

Returns whether another set contains this set or not

issuperset()

Returns whether this set contains another set or not

pop()

Removes an element from the set

remove()

Removes the specified element

symmetric_difference()

Returns a set with the symmetric differences of two sets

symmetric_difference_update()

inserts the symmetric differences from this set and another

union()

Return a set containing the union of sets

update()

Update the set with the union of this set and others

 

With this we come to an end of this article. Hope it was helpful. Do provide your feedback and ideas through comments, it would be highly appreciated. See you soon!
Keep coding and exploring new techs!!

 

 

 

0 comments:

Post a Comment