Question

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)        
Was it helpful?

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)

OTHER TIPS

Another option:

from operator import itemgetter
LL = list(itemgetter(*rand)(mylist))

Other options:

# just pick the items
from operator import itemgetter
print list(itemgetter(*rand)(mylist))

# pick 3 **actual** unique random items
from random import shuffle
shuffle(mylist)
print mylist[:3]

# Or as I've been reminded, and it preserves order of mylist (kudos @mgilson)
from random import sample
sample(mylist, 3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top