MyAI

Sets

Set is a collection of distinct objects. Objects in a set can be of any data type. Set in Python also a collection data type such as list or tuple.

set() is one of the built-in functions. It takes any sequence object (list, tuple or string) as argument and returns a set object

ex:

L1 = ["Rohan", "Physics", 21, 69.75]
s1 = set(L1)
T1 = (1, 2, 3, 4, 5)
s2 = set(T1)
string = "TutorialsPoint"
s3 = set(string)

print (s1)
print (s2)
print (s3)

The set() function returns a set object from the sequence, discarding the repeated elements in it. Set is a collection of distinct objects. Even if you repeat an object in the collection, only one copy is retained in it.

Since set is not a sequence data type, its items cannot be accessed individually as they do not have a positional index (as in list or tuple). Set items do not have a key either (as in dictionary) to access. You can only traverse the set items using a for loop.

myset = set()
myset.add(1)
print(myset)
myset.add(2)
print(myset)

myset.add(1)
print(myset)
#It will mot add 1 again as sets will consider only uniquw value 

mylist = [1,1,1,3,3,3,2,2,2,7,7,7,4,4,4]
mylist = set(mylist)
print(mylist)

#unorder collections of unique reference

s1={1,2,3,4,5}
s2={4,5,6,7,8}
s3 = s1|s2 # Joining sets
print (s3)

Result:

{1}
{1, 2}
{1, 2}
{1, 2, 3, 4, 7}
{1, 2, 3, 4, 5, 6, 7, 8}

Main Page   Next Chapter: Python - Arrays