Python Sets

Python Sets: Python set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined. Python’s set class represents the mathematical notion of a set. In Python, sets are written as curly braces. And the main advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.

NOTE: Sets are unordered, so the items will appear in a random order 

Example

thisset={"red","blue","green"} 
print(thisset)

Output: {‘red’, ‘blue’,’green’}

Python Sets

Python Sets

Frozen Sets

The frozen sets in python are nothing but the immutable objects which supports methods and operators that produces the result.

Example

#Python program to demonstrate differences 
#between normal and frozen set 
#Same as {"a", "b","c"} 
normal_set = set(["f", "r","e"]) 
#Adding an element to normal set is fine 
normal_set.add("d") 
print("Normal Set") 
print(normal_set) 
#A frozen set 
frozen_set = frozenset(["s", "h", "e"]) 
print("Frozen Set") 
print(frozen_set) 
#Uncommenting below line would cause error as 
#we are trying to add element to a frozen set 
#frozen_set.add("h") 

Output
Normal Set
set([‘r’, ‘e’, ‘d’, ‘f’])
Frozen Set
frozenset([‘h’, ‘s’, ‘e’])

Python Accessing items in Set

We cannot access items in a set by referring to an index, as we learned before that sets are unordered the items do not have an index. But if we want, we can loop through the set items using a for a loop. And we can also ask specified value is present in a set, by using the keyword.

Example

thisset={"red","pink","green"}
for x in thisset:print(x)

Output
pink green red

Change items in Python

You cannot change the items, once the set has been created. But if you want, we can add new items.

Add items in Python

To add an item to use the add( ) method.

Example

thisset={"van","car","bus"}
thisset.add("bike")
print(thisset)

Output: {‘van’,’car’, ‘bike’, ‘bus’}

If you want to add more than one item to a set use the update( ) method.

Example

thisset={"redmi","vivo","moto"}
thisset.update(["asus","lenovo","nokia"])
print(thisset)

Output: {‘lenovo’, ‘redmi’, ‘nokia’, ‘asus’, ‘vivo’, ‘moto}

Python Length of Set

To determine how many items in a set.

Example

thisset={"android","mac","windows"}

Output: 3

Remove Item in Python

If you want to remove an item is set, use remove (), or the discard () method.

Example

thisset={"android","mac","windows"}
thisset.remove("mac")
print(thisset)

Output: {‘android’,’windows’}

By using discard() in Python

Example

thisset={"android","mac","windows"}
thisset.discard("mac")
print(thisset)

Output: {‘android’, ‘windows’}

You can also use the pop( ) method, to remove an item, but this method will remove the last time. As, we learned before that sets are unordered, so you will be not knowing which element will be removed.

Example

thisset={"android","mac","windows"}
x=thiset.pop( )
print(x)
print(thisset)

Output: {‘mac’,’windows’}

Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.

Python Set Clear( )

It will empty the set.

Example

thiset={"telugu","english","tamil"}
thiset.clear( )
print(thiset)

Output: set( )

Python Set del( )

It deletes the set completely.

Example

thisset={"ind","aus","pak"}
thisset.clear()
print(thisset)

Output: Name Error: name ‘thisset’ is not defined #because the set no longer exists

Python Set( ) constructor

We can also make set( ) using constructor.

Example

thisset=set(("ind","aus","pak"))#note the double round-brackets 
print(thisset)

Output: {‘aus’,’ind’,’pak’} #sets are unordered, so the order will be changing

Python Set Methods

A method, in the context of object-oriented programming, is a procedure or a function in the class. As a part of the class, a method defines the behavior of class instance. A class can have more than one method.

Python has a set of built-in methods which can be used on sets

Method Description
add( ) It adds an element to the set
clear( ) removes all the elements from the set
copy( ) Returns a copy of the set
difference( ) returns set containing the difference between two or more sets
difference update( ) removes the items in the 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
isdisjoint( ) returns whether two sets have an 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

1) Python Set add( ) Method

The python add() method helps us to add items to a set if we want to place new elements.
Example
states = {“UP”, “MP”, “AP”}
states.add(“TN”)
Output
{‘UP’,  ‘MP’, ‘AP’, ‘TN’}

2) Python Set clear( ) Method

The clear( ) method helps us to clear the list.
Example

# Python program to clear a list 
# using clear() method 
# list of letters 
Freshers = [6, 0, 4, 1, 3, 5, 8, 2] 
print('Freshers before clear:', Freshers) 
# clearing vowels 
Freshers.clear() 
print('Freshers after clear:', Freshers) 

Output
Freshers before clear: [6, 0, 4, 1, 3, 5, 8, 2]
Freshers after clear: []

3) Python Set copy( ) Method

The copy( ) method in python helps us to copy the sets from one another.

Syntax:  list.copy()
Example

# Initializing list 
lis1 = [ 2, 5, 6, 4 ] 
# Using copy() to create a shallow copy 
lis2 = lis1.copy() 
# Printing new list 
print ("The new list created is : " + str(lis2)) 
# Adding new element to new list 
lis2.append(5) 
# Printing lists after adding new element 
# No change in old list 
print ("The new list after adding new element : " + str(lis2)) 
print ("The old list after adding new element to new list : " + str(lis1)) 

Output
The new list created is : [2, 5, 6, 4]
The new list after adding a new element : [2, 5, 6, 4, 5]
The old list after adding a new element to a new list : [2, 5, 6, 4]

4) Python Set difference( ) Method

The difference between the two sets in python is equal to the difference between the two elements in sets.

Syntax
set_A.difference(set_B) for (A – B)
set _B.difference(set_A) for (B – A)

Example

set A = {10, 20, 30, 40, 80}
set B = {100, 30, 80, 40, 60}
set A - set B = {10, 20}
set B - set A = {100, 60}

Output

python sets

5) Python Set differenceupdate( ) Method

The differenceupdate( ) method helps in an in-place way of differentiating the set.

Syntax

A.difference_update(B) for (A – B)
B.difference_update(A) for (B – A)

Example

#Python code to get the difference between two sets 
#using difference_update() between set A and set B   
# Driver Code 
A = {10, 20, 30, 40, 80} 
B = {100, 30, 80, 40, 60}  
#Modifies A and returns None 
A.difference_update(B) 
#Prints the modified set 
print (A)

Output
{20, 10}

6) Python Set discard( ) Method

It removes the element from the set only if the element is present in the set. If the element is not present in the set, then no error or exception is raised and the original set is printed.

Example

# Python program to remove random elements of choice 
# Function to remove elements using discard() 
def Remove(sets): 
    sets.discard(20) 
    print (sets) 
      
# Driver Code 
sets = set([10, 20, 26, 41, 54, 20]) 
Remove(sets) 

Output
{41, 10, 26, 54}

7) Python Set intersection( ) Method

The intersection( ) method tell us that the largest set which contains all the elements that are common to both the sets.

python intersection method

Example

Input: Let set A = {2, 4, 5, 6}
and set B = {4, 6, 7, 8}
Output: {4,6}

8) Python Set intersectionupdate( ) Method

The intresectionupdate method helps us to find the common elements in given arrays.

Example

# Function to find common elements in n arrays 
def commonElements(arr): 
      
    # initialize result with first array as a set 
    result = set(arr[0])
    for currSet in arr[1:]: 
        result.intersection_update(currSet)   
    return list(result) 
# Driver code 
if __name__ == "__main__": 
    arr = [[1,2,3,4], [8,7,3,2], [9,2,6,3], [5,1,2,3]] 
    output = commonElements(arr) 
    if len(output) > 0: 
        print output 
    else: 
        print 'No Common Elements Found'

Output
Common Elements = [2,3]

9) Python Set isdisjoint( ) Method

The isdisjoint( ) can be defined when their intersection is null.

Syntax: set1.isdisjoint(set2)

Example

#Python3 program for isdisjoint() function  
set1 = {2, 4, 5, 6}  
set2 = {7, 8, 9, 10} 
set3 = {1, 2}  
#checking of disjoint of two sets 
print("set1 and set2 are disjoint?", set1.isdisjoint(set2))   
print("set1 and set3 are disjoint?", set1.isdisjoint(set3)) 

Output
set1 and set2 are disjoint? True
set1 and set3 are disjoint? False

10) Python Set issubset( )

The issubset( ) method returns true if all the elements of set A are present in another set B which passed an argument and returns false if all the elements not present.

Syntax: A.issubset(B)

python issubset( )

Example

# Python program to demonstrate working of 
# issubset().   
A = {4, 1, 3, 5} 
B = {6, 0, 4, 1, 5, 0, 3, 5} 
# Returns True 
print(A.issubset(B)) 
# Returns False 
# B is not subset of A 
print(B.issubset(A))

Output
True
False

11) Python Set  issuperset( )

The issuperset( ) returns true if all the elements of set A occupy set B which is passed as an argument and also return false if elements of B is not present.

Syntax: A.issuperset(B)

python superset method

Example

# Python program to demonstrate the working of 
# issuperset().  
A = {4, 1, 3, 5} 
B = {6, 0, 4, 1, 5, 0, 3, 5}   
print("A.issuperset(B) : ", A.issuperset(B))   
# B is superset of A 
print("B.issuperset(A) : ", B.issuperset(A))

Output
A.issuperset(B) : False
B.issuperset(A) : True