Conor
Conor

Reputation: 670

Random Sample with remove from List

I have data in a list like:

L = [(3,4,5),(1,4,5),(1,2,3),(1,2,3)]

I need to sample randomly a size of 2 so I wanted to use:

import random
t1 = random.sample(set(L),2)

Now T1 is a List of the randomly pulled values, But i wanted to remove those randomly pulled from our initial list from our initial list. I could do a linear for loop but for the task I'm trying to do this for a larger list. so the Run time would take for ever!

Any suggestions on how to go about this?

Upvotes: 13

Views: 11798

Answers (2)

jvallver
jvallver

Reputation: 2340

One option is to shufle the list and then pop the first two elements.

import random
L = [(3,4,5),(1,4,5),(1,2,3),(1,2,3)]
random.shuffle(L)
t1 = L[0:2]

Upvotes: 13

eumiro
eumiro

Reputation: 212835

t1 = [L.pop(random.randrange(len(L))) for _ in xrange(2)]

doesn't change the order of the remaining elements in L.

Upvotes: 16

Related Questions