2

Given an array x = [2,3,5,4,1,7,4,2,8] I am looking to create a second array y which is a length p and consists of a random election of the elements within x. Is there an easier way other than doing the following

x = [2,3,5,4,1,7,4,2,8]
random.shuffle(x)
p = 5
y = x[0:p]
print y 
CJ12
  • 487
  • 2
  • 10
  • 28

1 Answers1

3

Use random.sample:

x = [2,3,5,4,1,7,4,2,8]
y = random.sample(x, p)
José Tomás Tocino
  • 9,873
  • 5
  • 44
  • 78