simultaneous assignment

Dave Hansen iddw at hotmail.com
Tue May 2 15:18:41 EDT 2006


On Tue, 02 May 2006 18:52:48 GMT in comp.lang.python, John Salerno
<johnjsal at NOSPAMgmail.com> wrote:

[...]
>
>Yeah, after trying some crazy things, I just wrote it this way:
>
>def truth_test(seq):
>     truth = 0
>     for item in seq:
>         if item:
>             truth += 1
>     if truth == 1:
>         return True
>     else:
>         return False

You could replace those last four lines with

      return truth == 1

>
>Not sure I like having to keep a counter though, but the other stuff I 

Well, if you want something minimalist, you could try

   def truth_test(seq):
      return sum(1 for item in seq if item) == 1

Though I'm not sure it's really any clearer...

>did was really convoluted, like checking to see if the first item was 
>True, and if it was, popping it from the list and iterating over the 
>rest of the items (needless to say, the in-place change wasn't helpful).

Perhaps something like

   def truth_test(seq):
      found = False
      for item in seq:
         if item:
            if found:
               return False
            found = True
      return found

Gets you an early exit, anyway...

All code untested.  Regards,
                                        -=Dave

-- 
Change is inevitable, progress is not.



More information about the Python-list mailing list