snippetpythonCritical
How to retrieve an element from a set without removing it?
Viewed 0 times
howsetwithoutelementretrieveremovingfrom
Problem
Suppose the following:
How do I get a value (any value) out of
Quick and dirty:
But do you know of a better way? Ideally in constant time.
>>> 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.
Solution
Two options that don't require copying the whole set:
Or...
But in general, sets don't support indexing or slicing.
for e in s:
break
# e is now an element from sOr...
e = next(iter(s))But in general, sets don't support indexing or slicing.
Code Snippets
for e in s:
break
# e is now an element from se = next(iter(s))Context
Stack Overflow Q#59825, score: 900
Revisions (0)
No revisions yet.