Sets in python

Document
Image description

SETS

Sets are an ideal choice for representing a group of unique values as a single entity. They offer several key characteristics: they do not allow duplicate elements, they do not preserve the order of insertion, and they do not support indexing or slicing. While the order of elements may not be guaranteed, sets can be sorted for specific purposes. This makes sets useful for tasks like removing duplicates from a list or performing set operations like union, intersection, and difference.

            
    s={10,20,30,40}
    print(s) 
               
     Ouput:{10,20,30,40}
            
        

Important set functions

add(x):

When we want to add individual element to the set we use add()

            
    ex:
    s={10,20,30}
    s.add(40);
    print(s) #{40, 10, 20, 30} 
                
            
        

update(x,y,z):

when we want to add multiple elements to the set we use update()

            
ex:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
                
x.update(y)
                
 print(x)

Output:
{'google', 'microsoft', 'apple', 
'banana', 'cherry'}
                
                   
            
        

Copy()

This set function is used when we want to copy the set

            
ex:
s={10,20,30}
s1=s.copy()
print(s1)
                
            
        

pop()

It removes and returns some random element from the set.

            
ex:
fruits = {"apple", "banana", "cherry"}
                
fruits.pop()
                
print(fruits)
                
output:
{'apple', 'cherry'}
                
            
        

remove()

The remove set function is used to remove the specified element from the set . If in case the element is not present in the set it returns keyerror.

            
ex:
s={40,10,30,20}
s.remove(30)
                
output:
{40,10,20}
                
            
        

Mathematical operation in set

union():

We can use this function to return all the elements present in the set

            
ex:
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y)) 
#{10, 20, 30, 40, 50, 60}
print(x|y) #{10, 20, 30, 40, 50, 60}
            
        

Intersection()

The intersection() is used to return the common element present in the sets.

            
ex:
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y)) #{40, 30}
print(x&y) #{40, 30}
                
            
        

Difference():

The difference() is used to return the elements presents in x and not in y

            
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y)) #{10, 20}
    print(x-y) #{10, 20}
print(y-x) #{50, 60}
            
        

Comments

Popular posts from this blog

Recursion In Python

Tkinter and Api