[Tutor] advice on idiom replacing if test requested

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Dec 12 05:13:00 CET 2005

On Sun, 11 Dec 2005, Brian van den Broek wrote:

> 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

Hi Brian,

This code works, and as long as you give it a good function name, I think
it's fine the way it is.

If we're concerned with efficiency, we might want to change the
random.choice() call to a random.randrange(), to avoid building the
concatenation of list1 and list2.  This looks like:

def sampleFromTwoLists(list1, list2):
    """Given two lists, returns a random element out of one of the lists
    as well as the other list."""
    index = random.randrange(len(list1) + len(list2))
    if index < len(list1):
        return list1[index], list2
         return list2[index - len(list1)], list1

Just out of curiosity, are you planning to do some kind of stratified
sampling with this?

> 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]

Too cute.  *grin* Although it's concise, I'm having a hard time reading

Talk to you later!

More information about the Tutor mailing list