Suppose the following:
>>> s = set([1, 2, 3])
How do I get a value (any value) out of s
without doing s.pop()
? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.
Quick and dirty:
>>> elem = s.pop()
>>> s.add(elem)
But do you know of a better way? Ideally in constant time.
I use a utility function I wrote. Its name is somewhat misleading because it kind of implies it might be a random item or something like that.
Seemingly the most compact (6 symbols) though very slow way to get a set element (made possible by PEP 3132):
With Python 3.5+ you can also use this 7-symbol expression (thanks to PEP 448):
Both options are roughly 1000 times slower on my machine than the for-loop method.
Another option is to use a dictionary with values you don't care about. E.g.,
You can treat the keys as a set except that they're just an array:
A side effect of this choice is that your code will be backwards compatible with older, pre-
set
versions of Python. It's maybe not the best answer but it's another option.Edit: You can even do something like this to hide the fact that you used a dict instead of an array or set:
I wondered how the functions will perform for different sets, so I did a benchmark:
This plot clearly shows that some approaches (
RandomSample
,SetUnpacking
andListIndex
) depend on the size of the set and should be avoided in the general case (at least if performance might be important). As already shown by the other answers the fastest way isForLoop
.However as long as one of the constant time approaches is used the performance difference will be negligible.
iteration_utilities
(Disclaimer: I'm the author) contains a convenience function for this use-case:first
:I also included it in the benchmark above. It can compete with the other two "fast" solutions but the difference isn't much either way.
How about
s.copy().pop()
? I haven't timed it, but it should work and it's simple. It works best for small sets however, as it copies the whole set.