Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What's the use case for set.pop()?

Tags:

python

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?

like image 926
Fabian Avatar asked Oct 15 '13 10:10

Fabian


1 Answers

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.

like image 118
Martijn Pieters Avatar answered Oct 14 '22 08:10

Martijn Pieters