Sets in Python
'''
Python Sets:
In Python, a set is an unordered collection of unique elements.
Sets are useful when we need to store a collection of items without any duplicates.
Key Characteristics of Sets:
1. Unordered: The items have no defined order, and their position can change.
2. Unique Elements: No duplicate values are allowed.
3. Mutable: Sets can be modified after creation (elements can be added or removed).
4. Heterogeneous: A set can contain elements of different data types.
'''
s1 = {1, 2, 3, 4}
print(s1) #output = {1, 2, 3, 4}
s2 = {1, 1, 2, 3, 4, 4}
print(s2) #output = {1, 2, 3, 4}
#Duplicates are automatically removed
info = {"Sindhu", 24, True, 2002}
print(info) #output = {24, True, 2002, 'Sindhu'}
#Here we can see that the items in set occur in random order, and hence they cannot be accessed using index numbers.
#info[0] #output = Typeerror: 'set' object is not subscriptable
harry = {} #An empty set
print(type(harry)) #output = <class 'dict'>
harry1 = set()
print(type(harry1)) #output = <class 'set'>
'''
Accessing Set Items:
We can access the items of set using a for-loop.
'''
for value in info:
print(value)
#output = 24
# True
# 2002
# Sindhu
Comments
Post a Comment