Python Set pop() Method (with Examples)

Python Set pop() Method: In this tutorial, we will learn about the pop() method of the set class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 14, 2023

Python Set pop() Method

The pop() is an inbuilt method of the set class that is used to remove a random element from the set, the method is called with this set and returns the removed element.

Syntax

The following is the syntax of pop() method:

set_name.pop()

Parameter(s):

The following are the parameter(s):

  • It does not accept any parameter.

Return Value

The return type of this method is the type of the element, it returns the removed/popped element.

Example 1: Use of Set pop() Method

# set
countries = {"Canada", "USA", "UK"}

# printing before calling pop()
print("countries (before):", countries)

# removing an element
ret = countries.pop()
print(ret, "is removed")

# printing after calling pop()
print("countries (after):", countries)

Output

countries (before): {'USA', 'Canada', 'UK'}
USA is removed
countries (after): {'Canada', 'UK'}

Example 2: Use of Set pop() Method

# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}
nums = {100, 200, 300, 400, 500}

# printing the sets before removing
print("Before the calling pop() method...")
print("cars: ", cars)
print("nums: ", nums)

# Removing/popping the elements from the sets
x = cars.pop()
print(x, "is removed from cars")
x = cars.pop()
print(x, "is removed from cars")
x = cars.pop()
print(x, "is removed from cars")

x = nums.pop()
print(x, "is removed from nums")
x = nums.pop()
print(x, "is removed from nums")
x = nums.pop()
print(x, "is removed from nums")

# printing the sets after removing
print("After the calling pop() method...")
print("cars: ", cars)
print("nums: ", nums)

Output

Before the calling pop() method...
cars:  {'Audi', 'Porsche', 'Lexus', 'Mazda', 'Lincoln'}
nums:  {100, 200, 300, 400, 500}
Audi is removed from cars
Porsche is removed from cars
Lexus is removed from cars
100 is removed from nums
200 is removed from nums
300 is removed from nums
After the calling pop() method...
cars:  {'Mazda', 'Lincoln'}
nums:  {400, 500}

Example 3: Using pop() Method with an Empty Set

If you remove an element from an empty set or there are no more elements to be deleted from a set, it will return a KeyError: 'pop from an empty set'. Consider below example -

# create an empty set
eset = set()

# printing it
print(eset)

# trying to call pop() with it
ret = eset.pop()
print("ret:", ret)

Output

set()
Traceback (most recent call last):
  File "/home/main.py", line 8, in <module>
    ret = eset.pop()
KeyError: 'pop from an empty set'


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.