Python: What's the Use Case for Set. Pop()?

Python: What's the Use Case for Set. Pop()?

The Python built-in type set has a method called pop(), from the docs:

Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.

I couldn't think of any use case for this feature, it seems to be an attempt to implement the list interface.

Why is this part of the Python standard?

1

1 Answer

You'd use it when you have a pool of jobs to process in no particular order. Jobs should only be executed once, but once executed can be added again:

jobs = {job1, job2, job3}

while jobs:
    job = jobs.pop()
    job.process()

where job.process() potentially adds more jobs to the pile. Once all jobs have been processed, the set will be empty and the loop is done.

Or, for a less contrived, real-world example, see the DependencyFinder.find() method from the distlib library (used by pip, for example), which uses a todo set to track distribution providers that still need processing.

The method is a mirror of the dict.popitem() method, which explicitly mentions set algorithms:

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms.

Before set was added to the language, you'd use a dictionary with None values to emulate a set.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.