bhylu.com

Advertisements

Remove Set Items

Choose removal behaviour according to whether a missing element is expected. discard tolerates absence, while remove raises KeyError.

Understand the idea

pop removes an arbitrary element, not the first inserted one, and raises KeyError on an empty set. clear removes every element from the existing object. These operations mutate the set, so aliases observe the change. Return information should not be confused with the updated container.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

tags = {"python", "web"}
tags.discard("missing")
tags.remove("web")
print(sorted(tags))

Read the result

The result contains only python. Discarding the absent label did not raise an error.

Try one change

Compare discard and remove for the same missing element inside a specific KeyError handler.