News for hackers. Stuff that matters.
Re:Python idiom for taking the single item from a list by orangecat on Monday September 27, 2010 @04:22PM (#1733223)
That fails for sets and other non-list iterables. It would have to be something like:

  def get_single(l):
      i = iter(l)
      val = i.next()
      try:
          i.next() # expected to throw exception for one-element iterable
      except StopIteration:
          return val
      raise AssertionError('More than one object')
Eww.
Re:Python idiom for taking the single item from a list by viraptor on Monday September 27, 2010 @05:19PM (#1733472)
You don't need to do that for a set. sets support `len()`. Also set supports `pop()`, so the code is very similar to the list one:

    assert s and len(s)==1
    return s.pop()
Or if you want to stay in the immutable land:

    assert s and len(s)==1
    return tuple(s)[0]
Re:Python idiom for taking the single item from a list by mccutchen on Monday September 27, 2010 @05:36PM (#1733546)
Both of those still fail for other non-list iterables, like generators.
Re:Python idiom for taking the single item from a list by robrenaud on Monday September 27, 2010 @10:45PM (#1734359)
They also have the side effect of removing an item from the collection.
Re:Python idiom for taking the single item from a list by lehmannro on Tuesday September 28, 2010 @06:14AM (#1735168)
A property which is exposed by the article's solution too:

   >>> x = (lambda: (yield 1))() # generator with one step
   >>> y = tuple(x)[0]
   >>> y
   1
   >>> list(x) # exhausted
   []

   >>> x = (lambda: (yield 1))()
   >>> y, = x
   >>> y
   1
   >>> list(x) # exhausted, too!
   []
Because that's just what you inevitably need to do to fetch a value from a generator. There is no peeking action or some such.
Re:Python idiom for taking the single item from a list by j_baker on Monday September 27, 2010 @08:17PM (#1734089)
Personally, I'm willing to restrict this to just lists to keep things simple. I rarely ever need a way to extract one value from a list, set, and iterable.