Download our e-book of Introduction To Python
Pallavi Dhotre
3 years ago
# Different sets in Python
# set of integers
demo_set = {1, 2, 3}
print(demo_set)
# set of mixed datatypes in python
demo_set = {11.0, "Hello World", (1, 2, 3)}
print(demo_set)
#using a set function in python
demo_set = set([10, 20, 30, 20])
print(demo_set)
{1, 2, 3}
{'Hello World', 11.0, (1, 2, 3)}
{10, 20, 30}
# set of integers
demo_set = {1, 2, 3}
print(demo_set)
demo_set.add(4) #adding single element to the set
print(demo_set)
demo_set.update([5,6,7]) #adding multiple elements to the set
print(demo_set)
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7}
# set of integers
demo_set = {1, 2, 3,4,5,6}
print(demo_set)
demo_set.discard(4) #discard element
print(demo_set)
demo_set.remove(7) #try to remove the element which is not present in a set
print(demo_set)
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 5, 6}
Traceback (most recent call last):
File "C:/Users/Pallavi/PycharmProjects/demo/demo1.py", line 8, in <module>
demo_set.remove(7) #try to remove the element which is not present in a set
KeyError: 7
# set of integers
demo_set = {1, 2, 3,4,5,6}
print(demo_set)
print(demo_set.pop()) #pop() method
{1, 2, 3, 4, 5, 6}
1
# set of integers
demo_set = {1, 2, 3,4,5,6}
print(demo_set)
demo_set.clear()
print(demo_set) #remove() method
{1, 2, 3, 4, 5, 6}
set()
demo_set1 = {1, 2, 3,4,5,6} #set1
demo_set2 = {11, 12, 13,14,15,16} #set2
print(demo_set1|demo_set2) #python set union using | operator
print(demo_set2.union(demo_set1)) #using union() method
{1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16}
{1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16}
demo_set1 = {1, 2, 3,4,5,6} #set1
demo_set2 = {1, 2, 13,14,15,16} #set2
print(demo_set1 & demo_set2) #python set intersection using & operator
print(demo_set2.intersection(demo_set1)) #using intersection() method
{1, 2}
{1, 2}
demo_set1 = {1, 2, 3,4,5,6} #set1
demo_set2 = {1, 2, 13,14,15,16} #set2
print(demo_set1 - demo_set2) #python set difference using - operator
print(demo_set1.difference(demo_set2)) #using function difference()
{3, 4, 5, 6}
{3, 4, 5, 6}
demo_set1 = {1, 2, 3,4,5,6} #set1
print(demo_set1)
set_to_list=list(demo_set1) #converting python set to list
print(set_to_list)
{1, 2, 3, 4, 5, 6}
[1, 2, 3, 4, 5, 6]
from ordered_set import OrderedSet
number = OrderedSet('198750') #using ordered set python
print(number)
OrderedSet(['1', '9', '8', '7', '5', '0'])