Python Language / Python Sets

It is a collection which is unordered and unindexed items and written with curly brackets.

Sample Programs
# Set Creation
ourset = ["Welcome to ", "Python", "Language"]
print(ourset)
Note: Sets are unordered so items appear in a random order.
["Welcome to ", "Python", "Language"]
# Accessing and printing set values using Loop
ourset = {"Welcome to ", "Python ", "Language "}
for x in ourset:
print(x)
Python Language

Welcome to
#check set exists / not
ourset = {"Welcome to ", "Python ", "Language "}
print("Python" in ourset)
True
# Add Items to set using add()
ourset = {"Welcome to ", "Python ", "Language "}
ourset.add("Server Side")
print(ourset)
{'Language', 'Welcome to', 'Server Side', 'Python'}
# Add Items to set using update() .
ourset = {"Welcome to", "Python", "Language"}
ourset. update(["Python ", "Version", "2"])
print(ourset)
{'2', 'Python', 'Welcome to', 'Version', 'Python ', 'Language'}
# Get the Set Length
ourset = {"Welcome to", "Python", "Language"}
print( len(ourset))
3
# Remove Item in a set using remove()
ourset = {"Welcome to", "Python", "Language"}
ourset.remove("Welcome to")
print(ourset)
{'Language', 'Python'}
# Remove Item in a set using discard ()
ourset = {"Welcome to", "Python", "Language"}
ourset. discard ("Welcome to")
print(ourset)
{'Language', 'Python'}
# Remove the last item by using the pop() method
ourset = {"Welcome to", "Python", "Language"}
x = class="pythonnumbercolor"> ourset.pop()
print(x)
Language
# clear() method to empty the set
ourset = {"Welcome to", "Python", "Language"}
ourset.clear()
print(ourset)
set()
# del keyword to Delete set
ourset = {"Welcome to", "Python", "Language"}
del class="pythonnumbercolor"> ourset
print(ourset)
name 'ourset' is not defined
# set() Constructorto create a new set.
ourset = set(("Welcome to", "Python", "Language"))
print(ourset)
{'Language', 'Welcome to', 'Python'}


Home     Back