0

Is there a way to 'get' the only item in a set without first casting it to a list?

s = set([u'http://imdb.com/title/tt0118583/'])
first_item = list(s)[0]
# u'http://imdb.com/title/tt0118583/'
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

5

You can use next(iter(setobj)) to get the only element:

>>> s = set([u'http://imdb.com/title/tt0118583/'])
>>> next(iter(s))
u'http://imdb.com/title/tt0118583/'

You can even specify a default for when the set is empty:

next(iter(setobj), None)

returns None if there is no element to return otherwise.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343