Click for All Topics
Syntax
set_name.pop()
Example 1 – let’s see an example
s={1,2,3,4,5}
print("Orginal set",s)
s.pop()
print("Modified set:",s)
# Ouput -
# Orginal set {1, 2, 3, 4, 5}
# Modified set: {2, 3, 4, 5}
In the above example, first we create a set s with the elements(1,2,3,4,5).
Example 2- In this example, we used the popped element from the set.
# print all odd elements of set
my_set={42,45,54,12,77,82,93,96}
print("Orginal set:",my_set)
for i in range(len(my_set)):
poped_ele=my_set.pop()
if poped_ele%2:
print(poped_ele)
# Output -
# Orginal set: {96, 42, 12, 45, 77, 82, 54, 93}
# 45
# 77
# 93
Example 3- Pop method with an empty set
s=set()
print(s)
s.pop()
# Output -
# set()
# Traceback (most recent call last):
# File "main.py", line 3, in
# s.pop()
# KeyError: 'pop from an empty set'
Example 4- Pop with argument
s={'this','is','edSlash'}
print(s)
s.pop('is')
# Output -
# {'this','is','edSlash'}
# Traceback (most recent call last):
# File "/home/main.py", line 3, in
# s.pop('is')
# TypeError: set.pop() takes no arguments (1 given)
Example 5-
city={'Bhind','Morena','Gwalior','Datia'}
print("Orginal set:",city)
poped_city=city.pop()
print("Modified set:",city)
print("Removed city from the set:",poped_city)
# Output -
# Orginal set: {'Bhind', 'Datia', 'Gwalior', 'Morena'}
# Modified set: {'Datia', 'Gwalior', 'Morena'}
# Removed city from the set: Bhind
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India