Search code examples
pythonlistrandomunique

Randomly chose an element of one list that's NOT in a second list


Say I have a list2 of randomly chosen elements from a large list1. Is there a clever way of choosing an element from list1 that's NOT already in list2?

For example:

list1 = range(20,100)
list2 = [37,49,22,35,72] # could be much longer
    
while True:
    n = random.choice(list1)
    if n not in list2:
        break
    
# now n is an element of list1 that's not in list2

I feel like there must be a more efficient way of doing this than a guess-and-check while-loop.


Solution

  • You can subtract list2 of list1:

    list3 = list(set(list1)-set(list2))
    

    and choose from it randomly:

    random.choice(list3)
    

    Note: you need to reconvert the set to a list.