Search code examples
pythonenumerate

Using enumerate to select random member of list


Lets say mylist is list of 70 elements, I would like to random select 0,12,5 elements from mylist. I get syntax error at "rand:"

rand = [0, 12, 5]
LL=[]
for x in enumerate(mylist) if i in rand:
        LL.append(x)        

Solution

  • Why not just:

    for i in rand:
       LL.append(mylist[i])
    

    Or better:

    LL = [mylist[i] for i in rand]
    

    But note that your code isn't well defined. I think what you were attempting was:

    LL = [ x for i,x in enumerate(mylist) if i in rand ]
    

    This will work, but it's unnecessary to iterate through the entire enumerated list unless you need to preserve the order from your original list.

    Finally, if you just want to randomly select N elements from your list, random.sample is perfect for that.

    import random
    LL = random.sample(mylist,3)