Python set - pop method

To remove an arbitrary element from a python set object use the pop method exposed by the pythons set object

Set Updated 16 Sep 2016 1 min read

Method Name

pop()

Method Overview

The pop() removes an arbitrary element from a python set object. If there are no elements in the set object, then a KeyError Exception will be raised.

Exception Handling

Raises a KeyError when the pop() method is invoked on an Empty Set

Example

python
>>> DeckOfCards = {'One',"Two","Three","Four","Five"}

>>> DeckOfCards.pop()

'Four'

>>> DeckOfCards.pop()

'Two'

>>> DeckOfCards.pop()

'Three'

>>> DeckOfCards.pop()

'One'

>>> DeckOfCards.pop()

'Five'

>>> DeckOfCards.pop()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

KeyError: 'pop from an empty set'