<br><br><div class="gmail_quote">On Sat, May 15, 2010 at 11:53 AM, Carl Banks <span dir="ltr"><<a href="mailto:pavlovevidence@gmail.com">pavlovevidence@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
<div class="im">On May 14, 9:39 am, Terry Reedy <<a href="mailto:tjre...@udel.edu">tjre...@udel.edu</a>> wrote:<br>
> On 5/14/2010 11:24 AM, gerardob wrote:<br>
><br>
><br>
><br>
</div><div class="im">> > Hello, let S be a python set which is not empty<br>
> > (<a href="http://docs.python.org/library/sets.html" target="_blank">http://docs.python.org/library/sets.html</a>)<br>
><br>
> > i would like to obtain one element (anyone, it doesn't matter which one) and<br>
> > assign it to a variable.<br>
><br>
> > How can i do this?<br>
><br>
</div><div class="im">> Depends on whether or not you want the element removed from the set<br>
><br>
> #3.1<br>
> >>> s=set(range(10))<br>
> >>> s<br>
> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}<br>
> >>> x=next(iter(s))<br>
> >>> x<br>
> 0<br>
> >>> s<br>
> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed<br>
> >>> x = s.pop()<br>
> >>> x<br>
> 0<br>
> >>> s<br>
> {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed<br>
><br>
> The choice of 0 is an implementation artifact. It could have been any<br>
> member.<br>
<br>
</div>Which brings up an interesting question: how do you get a random<br>
element from a set?<br>
<br>
random.choice(list(s))<br>
<br>
is the most straightforward way and will work a lot of the time, but<br>
how would you avoid creating the list? I can't think of a way off<br>
hand.<br>
<font color="#888888"><br></font></blockquote><div>How about random.sample(s, 1)[0]? Is it inefficient? <br></div><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
<font color="#888888">
<br>
Carl Banks<br>
</font><div><div></div><div class="h5"><br>
--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</div></div></blockquote></div><br><br clear="all"><br>-- <br>Regards<br>Shashank Singh<br>Senior Undergraduate, Department of Computer Science and Engineering<br>Indian Institute of Technology Bombay<br><a href="mailto:shashank.sunny.singh@gmail.com">shashank.sunny.singh@gmail.com</a><br>
<a href="http://www.cse.iitb.ac.in/~shashanksingh">http://www.cse.iitb.ac.in/~shashanksingh</a><br>