Python Set pop() Method with examples

Python Set pop

Now, we are going to learn about the pop method. The pop method is basically used to remove some element from the set, and it returns the removed element. We need not specify anything to this method. We just need to call the pop method on some set, and then it removes some element from the set and returns the removed element. Let’s have a look at a simple program, which tries to demonstrate the pop method.

Python Set pop() Method

As you can see, in the above program, we have a simple set, and then we are trying to call the pop method on the set. The pop method removes an element from the set and returns that removed element, so we are assigning the return value to a variable removed_element, and then we are printing that. Also, after that, we are also printing the set.

If you try to execute the above program and observe the output, you can find that the pop method has removed some element from the set and returned it, and then we are also printing the set, which does not contain that value. Let’s see the output in our case.

29

{87, 11, 45, 31}

As you can see, in our case, element 29 got removed from the set, and afterward, we are printing the set, and we can see that element 29 is not there in the set.

Note that the pop method randomly removes some elements from the set and returns the removed element. Also, if we are having an empty set, and we are trying to call the pop method on the empty set, then we are going to get an error. So, as and when required, we can make use of the pop method in our programs. Remember that the pop method removes some element from the set and returns the removed element.