Python set

Collection is another importantPythondata structure.

We can say that they work like tuples, but they are not ordered, they areVolatile. Or we can say that they work like dictionaries, but they have no keys.

They also have an unchanging version calledfrozenset.

You can create a collection using the following syntax:

names = {"Roger", "Syd"}

When you think of sets as mathematical sets, they work well.

You can intersect two sets:

set1 = {"Roger", "Syd"}
set2 = {"Roger"}

intersect = set1 & set2 #{‘Roger’}

You can create the union of two sets:

set1 = {"Roger", "Syd"}
set2 = {"Luna"}

union = set1 | set2 #{‘Syd’, ‘Luna’, ‘Roger’}

You can get the difference between the two groups:

set1 = {"Roger", "Syd"}
set2 = {"Roger"}

difference = set1 - set2 #{‘Syd’}

You can check whether a set is a superset of another set (of course, if one set is a subset of another set)

set1 = {"Roger", "Syd"}
set2 = {"Roger"}

isSuperset = set1 > set2 # True

you can use itlen()Global functions:

names = {"Roger", "Syd"}
len(names) # 2

You can get a list of items in the collection by passing the collection to the collection.list()Constructor:

names = {"Roger", "Syd"}
list(names) #['Syd', 'Roger']

you can use itinoperator:

print("Roger" in names) # True

More python tutorials: