Sets
- Set is unordered collection of Items, unordered means data can be saved randomly at any location, and not the way it was provided
#program
s1 = {10, 20, 30, 40, 50, 60, 70, 80, 90} # what trying to store
s2 = {9, 80, 7, 60, 5, 40, 3, 20, 1} # what trying to store
print("s1 : ", s1)
print("s2 : ", s2)
#output
s1 : {70, 40, 10, 80, 50, 20, 90, 60, 30} # how it got stored (unordered)
s2 : {1, 3, 5, 7, 40, 9, 80, 20, 60} # how it got stored (unordered)
- To declare Set, { } (curly brackets) are used.
Syntax :
Tuple_name = {member1, member2,..}
Tuple_name = {member1, member2,..}
#program
s1 = {10, 20, 30, 40, 50, 60, 70, 80, 90} # what trying to store
print("s1 : ", s1)
print("type(s1) : ", type(s1))
#output
s1 : {70, 40, 10, 80, 50, 20, 90, 60, 30} # how it got stored (unordered)
type(s1) : <class 'set'>
- Duplicates are not allowed.
#program
s1 = {10, 20, 30, 40, 50, 40, 30, 20, 10} # provided repeat items
print("s1 : ", s1)
#output
s1 : {40, 10, 50, 20, 30} #duplicates values not stored
- Accessing using indexing is not allowed, hence slice operator can not be used.
#program
s1 = {10, 20, 30, 40, 50, 40, 30, 20, 10} # provided repeat items
print("s1 : ", s1)
print("s1[2] : ", s[2])
#output
s1 : {40, 10, 50, 20, 30}
Traceback (most recent call last):
File "C:/Self_Practice_Er_M_S_Dandyan/Python/Pycharm/xml/main.py", line 5, in <module>
print("s1[2] : ", s[2])
NameError: name 's' is not defined
- Empty Set can not be declares, if do so will become a dictionary.
#program
s1 = {} # provided repeat items
print("s1 : ", s1)
print("type(s1) : ", type(s1))
#output
s1 : {}
type(s1) : <class 'dict'>
Set have some Built In Methods
Comments
Post a Comment