<p>Suppose the following:</p>

<pre><code>&gt;&gt;&gt; s = set([1, 2, 3])
</code></pre>

<p>How do I get a value (any value) out of <code>s</code> without doing <code>s.pop()</code>? 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.</p>

<p>Quick and dirty:</p>

<pre><code>&gt;&gt;&gt; elem = s.pop()
&gt;&gt;&gt; s.add(elem)
</code></pre>

<p>But do you know of a better way? Ideally in constant time.</p>

[{'answer_id': 59841, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 11, 'selected': True, 'text': "<p>Two options that don't require copying the whole set:</p>\n\n<pre><code>for e in s:\n    break\n# e is now an element from s\n</code></pre>\n\n<p>Or...</p>\n\n<pre><code>e = next(iter(s))\n</code></pre>\n\n<p>But in general, sets don't support indexing or slicing.</p>\n"}, {'answer_id': 59928, 'author': 'Pat Notz', 'author_id': 825, 'author_profile': 'https://Stackoverflow.com/users/825', 'pm_score': -1, 'selected': False, 'text': '<p>Another option is to use a dictionary with values you don\'t care about.  E.g.,</p>\n\n<pre><code>\npoor_man_set = {}\npoor_man_set[1] = None\npoor_man_set[2] = None\npoor_man_set[3] = None\n...\n</code></pre>\n\n<p>You can treat the keys as a set except that they\'re just an array:</p>\n\n<pre><code>\nkeys = poor_man_set.keys()\nprint "Some key = %s" % keys[0]\n</code></pre>\n\n<p>A side effect of this choice is that your code will be backwards compatible with older, pre-<code>set</code> versions of Python.  It\'s maybe not the best answer but it\'s another option.</p>\n\n<p>Edit: You can even do something like this to hide the fact that you used a dict instead of an array or set:</p>\n\n<pre><code>\npoor_man_set = {}\npoor_man_set[1] = None\npoor_man_set[2] = None\npoor_man_set[3] = None\npoor_man_set = poor_man_set.keys()\n</code></pre>\n'}, {'answer_id': 60027, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 5, 'selected': False, 'text': "<p>Since you want a random element, this will also work:</p>\n\n<pre><code>&gt;&gt;&gt; import random\n&gt;&gt;&gt; s = set([1,2,3])\n&gt;&gt;&gt; random.sample(s, 1)\n[2]\n</code></pre>\n\n<p>The documentation doesn't seem to mention performance of <code>random.sample</code>. From a really quick empirical test with a huge list and a huge set, it seems to be constant time for a list but not for the set. Also, iteration over a set isn't random; the order is undefined but predictable:</p>\n\n<pre><code>&gt;&gt;&gt; list(set(range(10))) == range(10)\nTrue \n</code></pre>\n\n<p>If randomness is important and you need a bunch of elements in constant time (large sets), I'd use <code>random.sample</code> and convert to a list first:</p>\n\n<pre><code>&gt;&gt;&gt; lst = list(s) # once, O(len(s))?\n...\n&gt;&gt;&gt; e = random.sample(lst, 1)[0] # constant time\n</code></pre>\n"}, {'answer_id': 60233, 'author': 'John', 'author_id': 2168, 'author_profile': 'https://Stackoverflow.com/users/2168', 'pm_score': 8, 'selected': False, 'text': '<p>Least code would be:</p>\n\n<pre><code>&gt;&gt;&gt; s = set([1, 2, 3])\n&gt;&gt;&gt; list(s)[0]\n1\n</code></pre>\n\n<p>Obviously this would create a new list which contains each member of the set, so not great if your set is very large.</p>\n'}, {'answer_id': 61140, 'author': 'Nick', 'author_id': 5222, 'author_profile': 'https://Stackoverflow.com/users/5222', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>def anyitem(iterable):\n    try:\n        return iter(iterable).next()\n    except StopIteration:\n        return None\n</code></pre>\n'}, {'answer_id': 1612654, 'author': 'wr.', 'author_id': 101430, 'author_profile': 'https://Stackoverflow.com/users/101430', 'pm_score': 5, 'selected': False, 'text': '<p>To provide some timing figures behind the different approaches, consider the following code.\n<em>The get() is my custom addition to Python\'s setobject.c, being just a pop() without removing the element.</em></p>\n\n<pre><code>from timeit import *\n\nstats = ["for i in xrange(1000): iter(s).next()   ",\n         "for i in xrange(1000): \\n\\tfor x in s: \\n\\t\\tbreak",\n         "for i in xrange(1000): s.add(s.pop())   ",\n         "for i in xrange(1000): s.get()          "]\n\nfor stat in stats:\n    t = Timer(stat, setup="s=set(range(100))")\n    try:\n        print "Time for %s:\\t %f"%(stat, t.timeit(number=1000))\n    except:\n        t.print_exc()\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>$ ./test_get.py\nTime for for i in xrange(1000): iter(s).next()   :       0.433080\nTime for for i in xrange(1000):\n        for x in s:\n                break:   0.148695\nTime for for i in xrange(1000): s.add(s.pop())   :       0.317418\nTime for for i in xrange(1000): s.get()          :       0.146673\n</code></pre>\n\n<p>This means that the <strong><em>for/break</em></strong> solution is the fastest (sometimes faster than the custom get() solution).</p>\n'}, {'answer_id': 34973737, 'author': 'AChampion', 'author_id': 2750492, 'author_profile': 'https://Stackoverflow.com/users/2750492', 'pm_score': 3, 'selected': False, 'text': '<p>Following @wr. post, I get similar results (for Python3.5)</p>\n\n<pre><code>from timeit import *\n\nstats = ["for i in range(1000): next(iter(s))",\n         "for i in range(1000): \\n\\tfor x in s: \\n\\t\\tbreak",\n         "for i in range(1000): s.add(s.pop())"]\n\nfor stat in stats:\n    t = Timer(stat, setup="s=set(range(100000))")\n    try:\n        print("Time for %s:\\t %f"%(stat, t.timeit(number=1000)))\n    except:\n        t.print_exc()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Time for for i in range(1000): next(iter(s)):    0.205888\nTime for for i in range(1000): \n    for x in s: \n        break:                                   0.083397\nTime for for i in range(1000): s.add(s.pop()):   0.226570\n</code></pre>\n\n<p>However, when changing the underlying set (e.g. call to <code>remove()</code>) things go badly for the iterable examples (<code>for</code>, <code>iter</code>):</p>\n\n<pre><code>from timeit import *\n\nstats = ["while s:\\n\\ta = next(iter(s))\\n\\ts.remove(a)",\n         "while s:\\n\\tfor x in s: break\\n\\ts.remove(x)",\n         "while s:\\n\\tx=s.pop()\\n\\ts.add(x)\\n\\ts.remove(x)"]\n\nfor stat in stats:\n    t = Timer(stat, setup="s=set(range(100000))")\n    try:\n        print("Time for %s:\\t %f"%(stat, t.timeit(number=1000)))\n    except:\n        t.print_exc()\n</code></pre>\n\n<p>Results in:</p>\n\n<pre><code>Time for while s:\n    a = next(iter(s))\n    s.remove(a):             2.938494\nTime for while s:\n    for x in s: break\n    s.remove(x):             2.728367\nTime for while s:\n    x=s.pop()\n    s.add(x)\n    s.remove(x):             0.030272\n</code></pre>\n'}, {'answer_id': 40054478, 'author': 'Cecil Curry', 'author_id': 2809027, 'author_profile': 'https://Stackoverflow.com/users/2809027', 'pm_score': 6, 'selected': False, 'text': '<h2>tl;dr</h2>\n\n<p><code>for first_item in muh_set: break</code> remains the optimal approach in Python 3.x. <sup><em>Curse you, Guido.</em></sup></p>\n\n<h2>y u do this</h2>\n\n<p>Welcome to yet another set of Python 3.x timings, extrapolated from <a href="https://stackoverflow.com/users/101430/wr">wr.</a>\'s excellent <a href="https://stackoverflow.com/a/1612654/2809027">Python 2.x-specific response</a>. Unlike <a href="https://stackoverflow.com/users/2750492/achampion">AChampion</a>\'s equally helpful <a href="https://stackoverflow.com/a/34973737/2809027">Python 3.x-specific response</a>, the timings below <em>also</em> time outlier solutions suggested above – including:</p>\n\n<ul>\n<li><code>list(s)[0]</code>, <a href="https://stackoverflow.com/users/2168/john">John</a>\'s novel <a href="https://stackoverflow.com/a/60233/2809027">sequence-based solution</a>.</li>\n<li><code>random.sample(s, 1)</code>, <a href="https://stackoverflow.com/users/3002/df">dF.</a>\'s eclectic <a href="https://stackoverflow.com/a/60027/2809027">RNG-based solution</a>.</li>\n</ul>\n\n<h2>Code Snippets for Great Joy</h2>\n\n<p>Turn on, tune in, time it:</p>\n\n<pre><code>from timeit import Timer\n\nstats = [\n    "for i in range(1000): \\n\\tfor x in s: \\n\\t\\tbreak",\n    "for i in range(1000): next(iter(s))",\n    "for i in range(1000): s.add(s.pop())",\n    "for i in range(1000): list(s)[0]",\n    "for i in range(1000): random.sample(s, 1)",\n]\n\nfor stat in stats:\n    t = Timer(stat, setup="import random\\ns=set(range(100))")\n    try:\n        print("Time for %s:\\t %f"%(stat, t.timeit(number=1000)))\n    except:\n        t.print_exc()\n</code></pre>\n\n<h2>Quickly Obsoleted Timeless Timings</h2>\n\n<p><strong>Behold!</strong> Ordered by fastest to slowest snippets:</p>\n\n<pre><code>$ ./test_get.py\nTime for for i in range(1000): \n    for x in s: \n        break:   0.249871\nTime for for i in range(1000): next(iter(s)):    0.526266\nTime for for i in range(1000): s.add(s.pop()):   0.658832\nTime for for i in range(1000): list(s)[0]:   4.117106\nTime for for i in range(1000): random.sample(s, 1):  21.851104\n</code></pre>\n\n<h2>Faceplants for the Whole Family</h2>\n\n<p>Unsurprisingly, <strong>manual iteration remains at least twice as fast</strong> as the next fastest solution. Although the gap has decreased from the Bad Old Python 2.x days (in which manual iteration was at least four times as fast), it disappoints the <a href="https://www.python.org/dev/peps/pep-0020/" rel="noreferrer">PEP 20</a> zealot in me that the most verbose solution is the best. At least converting a set into a list just to extract the first element of the set is as horrible as expected. <em>Thank Guido, may his light continue to guide us.</em></p>\n\n<p>Surprisingly, the <strong>RNG-based solution is absolutely horrible.</strong> List conversion is bad, but <code>random</code> <em>really</em> takes the awful-sauce cake. So much for the <a href="http://catb.org/esr/jargon/html/R/Random-Number-God.html" rel="noreferrer">Random Number God</a>.</p>\n\n<p>I just wish the amorphous They would PEP up a <code>set.get_first()</code> method for us already. If you\'re reading this, They: "Please. Do something."</p>\n'}, {'answer_id': 45803038, 'author': 'skovorodkin', 'author_id': 847552, 'author_profile': 'https://Stackoverflow.com/users/847552', 'pm_score': 4, 'selected': False, 'text': '<p>Seemingly the <strong>most compact</strong> (6 symbols) though <strong>very slow</strong> way to get a set element (made possible by <a href="https://www.python.org/dev/peps/pep-3132/" rel="noreferrer">PEP 3132</a>):</p>\n\n<pre><code>e,*_=s\n</code></pre>\n\n<p>With Python 3.5+ you can also use this 7-symbol expression (thanks to <a href="https://www.python.org/dev/peps/pep-0448/" rel="noreferrer">PEP 448</a>):</p>\n\n<pre><code>[*s][0]\n</code></pre>\n\n<p>Both options are roughly 1000 times slower on my machine than the for-loop method.</p>\n'}, {'answer_id': 48874729, 'author': 'MSeifert', 'author_id': 5393381, 'author_profile': 'https://Stackoverflow.com/users/5393381', 'pm_score': 7, 'selected': False, 'text': '<p>I wondered how the functions will perform for different sets, so I did a benchmark:</p>\n\n<pre><code>from random import sample\n\ndef ForLoop(s):\n    for e in s:\n        break\n    return e\n\ndef IterNext(s):\n    return next(iter(s))\n\ndef ListIndex(s):\n    return list(s)[0]\n\ndef PopAdd(s):\n    e = s.pop()\n    s.add(e)\n    return e\n\ndef RandomSample(s):\n    return sample(s, 1)\n\ndef SetUnpacking(s):\n    e, *_ = s\n    return e\n\nfrom simple_benchmark import benchmark\n\nb = benchmark([ForLoop, IterNext, ListIndex, PopAdd, RandomSample, SetUnpacking],\n              {2**i: set(range(2**i)) for i in range(1, 20)},\n              argument_name=\'set size\',\n              function_aliases={first: \'First\'})\n\nb.plot()\n</code></pre>\n\n<p><a href="https://i.stack.imgur.com/7oqB6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7oqB6.png" alt="enter image description here"></a></p>\n\n<p>This plot clearly shows that some approaches (<code>RandomSample</code>, <code>SetUnpacking</code> and <code>ListIndex</code>) depend on the size of the set and should be avoided in the general case (at least if performance <em>might</em> be important). As already shown by the other answers the fastest way is <code>ForLoop</code>.</p>\n\n<p>However as long as one of the constant time approaches is used the performance difference will be negligible.</p>\n\n<hr>\n\n<p><a href="https://iteration-utilities.readthedocs.io/en/latest/index.html" rel="noreferrer"><code>iteration_utilities</code></a> (Disclaimer: I\'m the author) contains a convenience function for this use-case: <a href="https://iteration-utilities.readthedocs.io/en/latest/generated/first.html" rel="noreferrer"><code>first</code></a>:</p>\n\n<pre><code>&gt;&gt;&gt; from iteration_utilities import first\n&gt;&gt;&gt; first({1,2,3,4})\n1\n</code></pre>\n\n<p>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.</p>\n'}, {'answer_id': 49138346, 'author': 'Solomon Ucko', 'author_id': 5445670, 'author_profile': 'https://Stackoverflow.com/users/5445670', 'pm_score': -1, 'selected': False, 'text': "<p>How about <code>s.copy().pop()</code>? 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.</p>\n"}, {'answer_id': 60803131, 'author': 'Josué Carvajal', 'author_id': 5911191, 'author_profile': 'https://Stackoverflow.com/users/5911191', 'pm_score': 2, 'selected': False, 'text': '<p>What I usually do for small collections is to create kind of parser/converter method like this</p>\n\n<pre><code>def convertSetToList(setName):\nreturn list(setName)\n</code></pre>\n\n<p>Then I can use the new list and access by index number</p>\n\n<pre><code>userFields = convertSetToList(user)\nname = request.json[userFields[0]]\n</code></pre>\n\n<p>As a list you will have all the other methods that you may need to work with</p>\n'}, {'answer_id': 64224698, 'author': 'seralouk', 'author_id': 5025009, 'author_profile': 'https://Stackoverflow.com/users/5025009', 'pm_score': 2, 'selected': False, 'text': '<p><strong>You can unpack the values to access the elements:</strong></p>\n<pre><code>s = set([1, 2, 3])\n\nv1, v2, v3 = s\n\nprint(v1,v2,v3)\n#1 2 3\n</code></pre>\n'}, {'answer_id': 64352862, 'author': 'dzang', 'author_id': 7812912, 'author_profile': 'https://Stackoverflow.com/users/7812912', 'pm_score': 4, 'selected': False, 'text': '<p>Yet another way in Python 3:</p>\n<pre><code>next(iter(s))\n</code></pre>\n<p>or</p>\n<pre><code>s.__iter__().__next__()\n</code></pre>\n'}, {'answer_id': 65430015, 'author': 'Necho', 'author_id': 3558704, 'author_profile': 'https://Stackoverflow.com/users/3558704', 'pm_score': 0, 'selected': False, 'text': '<p>I f you want just the first element try this:\nb = (a-set()).pop()</p>\n'}]
['https://Stackoverflow.com/questions/59825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2260/']