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?
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?
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
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.
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.