2
rand_arr=[0, ]
def rand_key_gen(arr):
    for x in range(0, 25):
        rand_arr[x] = random.choice(arr)

This is incomplete. But the problem here is that I might get the same value again. How do I circumvent this situation?

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • So to clarify, you want each item from `arr` to appear once in `rand_arr`? (also for the record in Python they're called lists) – SuperBiasedMan Nov 18 '15 at 15:42

3 Answers3

2

You can use random.shuffle to achieve a shuffled list from the original list. But as it mutate the original list, make a copy of original list first.

import random
shuffled_lst=lst[:]
random.shuffle(shuffled_lst)
print "Reshuffled list : ", shuffled_lst
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
2

You'd use random.sample. It will select the required number of non-repeating elements from arr:

import random
rand_arr = [0]
def rand_key_gen(arr):
    rand_arr[:] = random.sample(arr, 25)

There's no need for the loop, since you can modify rand_arr via slice assigment.

Community
  • 1
  • 1
vaultah
  • 44,105
  • 12
  • 114
  • 143
1

What about using random.shuffle:

from random import shuffle

new_list = old_list[:]  # copy
shuffle(new_list)
print(new_list)

If you want a smaller list, you can use slicing.

abrunet
  • 1,122
  • 17
  • 31