[Tutor] advice on idiom replacing if test requested

bob bgailer at alum.rpi.edu
Mon Dec 12 03:58:09 CET 2005


At 04:15 PM 12/11/2005, Brian van den Broek wrote:
>Hi all,
>
>I have a case like this toy code:
>
>import random
>list1 = [1,2,3]
>list2 = ['a', 'b', 'c']
>item = random.choice(list1 +list2)
>if item in list1:
>      others = list2
>else:
>      others = list1
>
>
>Another way occurred to me, but I wonder if I'm being too cute:
>
>item = random.choice(list1 +list2)
>others = [list1, list2][item in list1]
>
>I believe we can rely on True and False being 1 and 0 until Python
>3.0. But, even assuming that's right, I wonder if it is obscure to others.

It is not obscure to me. I do tings like that all the time.

But I think your algorithm is unnecessarily complex and costly. Consider

import random
list1 = [1,2,3]
list2 = ['a', 'b', 'c']
len1 = len(list1)
len2 = len(list2)
item = random.randint(1, len1 + len2)
if item <= len1:
      others = list2
else:
      others = list1

But then we also could:

import random
... same as above
lists = [list1, list2]
others = lists[random.randint(1, len1 + len2) <= len1]



More information about the Tutor mailing list