News for hackers. Stuff that matters.
Re:Python idiom for taking the single item from a list by j_baker on Monday September 27, 2010 @03:30PM (#1733007)
Personally, I think this is a bit on the "clever" side. Plus, the error message you get isn't as easy to understand as if you used an assert statement. I'd probably just do something like this:

    def get_single(l):
        assert l and len(l) == 1
        return l[0]
Then you get the best of both worlds: readability and a concise one-liner.
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.
Re:Python idiom for taking the single item from a list by cool-RR on Monday September 27, 2010 @03:39PM (#1733037)
I'd avoid doing this, because people who'll read your code would have to check themselves what the `get_single` function does.

Also, the performance here is probably much worse. (Although in many cases it would not matter.)

But that's just my opinion, your suggestion is legitimate.

Re:Python idiom for taking the single item from a list by jemfinch on Monday September 27, 2010 @04:44PM (#1733336)
> I'd avoid doing this, because people who'll read your code would have to check themselves what the `get_single` function does.

This is an argument against using functions at all. If it works against get_single, it works against all functions.

That is to say, it doesn't work at all.

Re:Python idiom for taking the single item from a list by cool-RR on Monday September 27, 2010 @05:01PM (#1733400)
Yes, but with most functions there's no choice, because most of the functions in your program do something (a) complex and/or (b) specific to your program. This `get_single` function falls into neither of these categories.
Re:Python idiom for taking the single item from a list by jemfinch on Monday September 27, 2010 @05:24PM (#1733501)
Functions should not be complex. Functions should be simple, and they should be composed by other simple functions to do more complex things.
Re:Python idiom for taking the single item from a list by Scriptor on Monday September 27, 2010 @05:42PM (#1733566)
It is certainly okay for some functions to be complex. Some may rely on simpler functions, but the one you'd use can still do a complex task in general.

A function that squares a number is simple, one that computes the standard deviation is definitely more complex.

Re:Python idiom for taking the single item from a list by jemfinch on Monday September 27, 2010 @06:40PM (#1733793)
> A function that squares a number is simple, one that computes the standard deviation is definitely more complex.

I'm talking about the complexity difference between this:

  def stddev(pop):
    total = 0
    count = 0
    for x in pop:
      total += x
      count += 1
    mean = total / float(count)
    variance = 0
    for x in pop:
      variance += (x - mean)**2
    return math.sqrt(variance)
    
and this:

    def stddev(pop):
      return math.sqrt(variance(pop))

    def variance(pop):
      m = mean(pop)
      return sum(square(x - m) for x in pop)

    def mean(pop):
      return sum(pop) / float(len(pop))

    def square(x):
      return x**2
The first is a (mildly) complex function. The latter are all simple functions, and the complex result is constructed by composing simple operations.

Good programmers write functions in the latter style, not the former.

Re:Python idiom for taking the single item from a list by orangecat on Monday September 27, 2010 @08:51PM (#1734167)
Good programmers write functions in the latter style, not the former.

Well, that stddev function could be much less verbose:

    def stddev(pop):
        mean = sum(pop) / float(len(pop))
        variance = sum( (x-mean)**2 for x in pop)
        return math.sqrt(variance)
To me that's easier to read than jumping back and forth between multiple function definitions. Of course, if you need the mean or variance independently then your way is better.
Re:Python idiom for taking the single item from a list by jemfinch on Monday September 27, 2010 @10:42PM (#1734355)
> Well, that stddev function could be much less verbose:

Sure, it could, but I was demonstrating what it looked like without the use of functions. Your example proves my point just as mine does: sum(), like mean() or variance() in my example, is just a simple function, the kind that I'm arguing for. The fact that it's built into Python (rather recently, I note) doesn't change that fact or reduce the impact of the argument. Your example simply goes one step down the path, and mine goes further.

> To me that's easier to read than jumping back and forth between multiple function definitions.

You don't have to jump back and forth between function definitions. Let's say you don't know what the standard deviation is, but you know what the mean is. You can look at the definition of stddev() and see, "Ah, it's clearly the sqrt() of the variance. What's the variance? Ah, it's the sum of the squares of difference between each element and the mean." You know what the mean() does (its name is pretty clear) and you know what sum() and square() do, so you never have to look at those functions. Someone else who knows what the variance is would never have to look that deep. When someone is reading the stddev() in my example, he doesn't have concern himself with implementation details of functions he already understands. When someone is reading yours, he has to at least read how the mean is calculated. He can't avoid it--it's right there.

> Of course, if you need the mean or variance independently then your way is better.

You almost certainly will in any case where you're using the standard deviation, but that's just an artifact of the example. Other advantages of using small, simple functions like in my example:

* More reusable (as you noted) * More easily testable. * More easily comprehensible (as I showed above) * More easily documented (especially in a language like Python with its docstring support) * More conceptual abstraction

Re:Python idiom for taking the single item from a list by jemfinch on Monday September 27, 2010 @04:43PM (#1733328)
> assert l and len(l) == 1

This is redundant: if a list's length is 1, then it's true in a boolean context.

Also, please stop naming your lists 'l'. On a vast array of fonts, it differs only in a few pixels from '1'. Use "L" instead :)

Re:Python idiom for taking the single item from a list by statictype on Monday September 27, 2010 @08:59PM (#1734192)
This is redundant: if a list's length is 1, then it's true in a boolean context.

In a boolean context, the list is true if the length is non-zero. This example and the one the article is about is for the case where you know the list to have exactly one element. Not zero and not more than one.

Re:Python idiom for taking the single item from a list by jemfinch on Tuesday September 28, 2010 @12:17AM (#1734543)
You are aware that asserting `len(L) == 1` excludes the possibility that it's empty, right? You know what "redundant" means, right?
Re:Python idiom for taking the single item from a list by statictype on Tuesday September 28, 2010 @01:51AM (#1734724)
if L is None then asserting `len(L)==1` throws an exception.

The `if L and` part safeguards against that.

Re:Python idiom for taking the single item from a list by jemfinch on Tuesday September 28, 2010 @01:46PM (#1736518)
And the point that was made in the other branch of this thread is that if the author intends to guard against None (who knows why?) then he should say, explicitly, "if L is not None". That's what PEP8 recommends precisely to avoid ambiguities such as these.
Re:Python idiom for taking the single item from a list by durin42 on Monday September 27, 2010 @04:54PM (#1733372)
He's defending against None with the assert l and len(l) bit, or at least that's what I'd assume.
Re:Python idiom for taking the single item from a list by swolchok on Monday September 27, 2010 @05:18PM (#1733468)
If he's defending against None, he should

    assert l is not None and len(l) == 1
Re:Python idiom for taking the single item from a list by dirtyaura on Tuesday September 28, 2010 @02:05AM (#1734744)
There's a better variable naming scheme for generic lists:

Use xs. If you have multiple lists use ys etc.

This has multiple benefits over L in terms of readability anad understandability as a single-item variable names can be made to match the list naming scheme:

  for x in xs: 
     for y in ys: 
        do_some_fancy_calculation(x,y)
Re:Python idiom for taking the single item from a list by j_baker on Monday September 27, 2010 @05:01PM (#1733404)
I wouldn't name a list l in real code. It was just the first thing that popped to mind. :-)

And as was mentioned the "assert l" part is defending against l being None. I suppose I could be more explicit by saying "assert l is not None and len(l) == 1".

Re:Python idiom for taking the single item from a list by jemfinch on Monday September 27, 2010 @05:26PM (#1733507)
Yes, you should definitely should be more explicit if that's what you intend to check: PEP8 makes that explicit.

I'm not sure why you'd defend against None anyway. Why defend against None, but not against 3.1459 or 4j or ''?

Re:Python idiom for taking the single item from a list by statictype on Monday September 27, 2010 @08:57PM (#1734182)
There's nothing wrong with `is l`. Sounds like you're just splitting hairs.

He's defending against None because calling __len__ on None results in an exception.

3.14159 also results in an exception but it's far more likely that the object passed was None than that it was a completely different type than the one expected.

Re:Python idiom for taking the single item from a list by jemfinch on Tuesday September 28, 2010 @04:24PM (#1737146)
> it's far more likely that the object passed was None than that it was a completely different type than the one expected.

FYI, None is a completely different type than the one expected.

Re:Python idiom for taking the single item from a list by beaumartinez on Tuesday September 28, 2010 @07:44AM (#1735346)
Create a wrapper function for a one-line statment? Sure, it's more readable, but it's Unpythonic.