How to get an item from a simple set?
Bengt Richter
bokr at oz.net
Wed Nov 24 12:14:14 EST 2004
On Wed, 24 Nov 2004 09:46:50 -0600, Skip Montanaro <skip at pobox.com> wrote:
>
> Pete> I have a set that contains one item. What is the best way of
> Pete> getting at that item? Using pop() empties the set.
>
>Do you want to enumerate all the items in the set? If so:
>
> for elt in s:
> print elt
>
>If you just want to grab one arbitrary (though not random) item from the
>set, try:
>
> elt = iter(s).next()
>
>Note that repeating this operation will always return the same item:
>
> >>> s
> set(['jkl', 'foo', 'abc', 'def', 'ghi'])
> >>> iter(s).next()
> 'jkl'
> >>> iter(s).next()
> 'jkl'
> >>> iter(s).next()
> 'jkl'
> >>> iter(s).next()
> 'jkl'
>
Lest someone else not realize that the operation you are repeating includes creating
a fresh initialized iterator each time, and you're just doing it as a way to grab one element:
>>> s = set(['jkl', 'foo', 'abc', 'def', 'ghi'])
>>> it = iter(s)
>>> it.next()
'jkl'
>>> it.next()
'foo'
>>> it.next()
'abc'
>>> it.next()
'def'
>>> it.next()
'ghi'
>>> it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
Regards,
Bengt Richter
More information about the Python-list
mailing list