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?

1
  • 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) Commented Nov 18, 2015 at 15:42

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.