New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Retrieve an arbitrary element from a set without removing it #51461
Comments
Sometimes, a non-removing pop() is needed. In current Python versions, x = some_set.pop() for x in some_set: x = iter(some_set).next() More native and clean would, however, be The attached patch does this for set(). If this is accepted by the |
Without tests, this patch is unacceptable. |
added tests for get() to test_set.py |
Any reason you don't want to call set_next from set_get? I would say static PyObject *
set_get(PySetObject *so)
{
register Py_ssize_t pos = 0;
register setentry *entry;
if (set_next(so, &pos, &entry)) {
Py_INCREF(entry->key);
return entry->key;
}
/* set appropriate error */
return NULL;
} BTW, what your patch is supposed to do on set().get()? |
No particular reason, besides that it is ripped off of pop(). Your solution (omitting "register") gives the same performance. Looks The patch tries to provide a clean way of "for x in some_set: break", as |
After a long discussion on python-dev, this proposal is rejected in Here is an except from the end of the thread: [Steven D'Aprano]
[geremy condra]
[Raymond]
[Terry Reedy] [Raymond] [Eric Smith] [Terry Reedy] Leaving this open until I've done the documentation patch. |
I don't want to pollute python-dev with more hopeless ideas, but I wonder def first(collection):
return next(iter(collection)) On the other hand, it probably belongs to recipes more than stdlib. This |
I still see a use in this. I like to use sets for lists of servers or mirrors. There is no compelling reason *not* to add a get() or pick() method, as described in http://en.wikipedia.org/wiki/Set_%28computer_science%29. Sets could be used for many things that lists are currently used for. I request for this to be reopened given the lapse since any action on this. |
I support http://bugs.python.org/msg94599 with a check to see if the length is 0, and rename it pick (based on the generic programming and mathematical literature). |
Use set.pop(). Or if you don't want mutation, then use next(iter(s)) or next(iter(s),default). This technique also works for any collection including dicts and deques and whatnot. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: