python remove item from set code example

Example 1: python set remove

s = {0, 1, 2}
s.discard(0)  
print(s)
{1, 2}

# discard() does not throw an exception if element not found
s.discard(0)

# remove() will throw
s.remove(0)
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 0

Example 2: remove an item from a set python

# it doesn't raise error if element doesn't exits in set

thisset = {1, 2,3}

thisset.discard(3)

print(thisset)

Example 3: python remove to set

s = set()
s.remove(x)

Example 4: delete and return element from set python

>>> s = set([1])
>>> print s.pop()
1
>>> print s
set([])
>>> print s.pop()
KeyError: pop from an empty set

Example 5: remove an element from a set

list.remove(element)

Tags:

Misc Example