Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError: 'pop from an empty set' python

Tags:

python

set

How do you get around this error while using .pop? I get that when it tries to return a number but there isn't one an error is raised but how do you get around it so the program keeps running?

def remove_element(self,integer):
    self.integer = integer
    self.members.pop()
like image 335
Jen Avatar asked Sep 06 '25 03:09

Jen


2 Answers

Just check if self.members is not empty:

if self.members:
    self.members.pop()

or, catch KeyError via try/except:

try:
    self.members.pop()
except KeyError:
    # do smth
like image 176
alecxe Avatar answered Sep 07 '25 20:09

alecxe


You can use try/except to catch the KeyError raised by an_empty_set.pop(), or check the set first to make sure it's not empty:

if s:
    value = s.pop()
else:
    # whatever you want to do if the set is empty
like image 22
Tim Peters Avatar answered Sep 07 '25 19:09

Tim Peters