Python

pop method in set

Click for All Topics

pop method in set - Python

  • The pop method is used to remove or pop an element from a set.
  • It doesn’t take any argument.
  • This method returns the popped element.
  • It removes the element randomly.
  • It will raise an error when popping an element from an empty set.

 

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).

  • Then print the original set s on the output screen.
  • Then we call the pop method with set s it removes the element(1) from set s.
  • Finally, we print the modified original set on the output screen.

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 <module>
    # 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 <module>
    # 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