How do I create a list of random numbers without duplicates?
This will return a list of 10 numbers selected from the range 0 to 99, without duplicates.
import random
random.sample(range(100), 10)
With reference to your specific code example, you probably want to read all the lines from the file once and then select random lines from the saved list in memory. For example:
all_lines = f1.readlines()
for i in range(50):
lines = random.sample(all_lines, 40)
This way, you only need to actually read from the file once, before your loop. It's much more efficient to do this than to seek back to the start of the file and call f1.readlines()
again for each loop iteration.
You can use the shuffle function from the random module like this:
import random
my_list = list(xrange(1,100)) # list of integers from 1 to 99
# adjust this boundaries to fit your needs
random.shuffle(my_list)
print my_list # <- List of unique random numbers
Note here that the shuffle method doesn't return any list as one may expect, it only shuffle the list passed by reference.
You can first create a list of numbers from a
to b
, where a
and b
are respectively the smallest and greatest numbers in your list, then shuffle it with Fisher-Yates algorithm or using the Python's random.shuffle
method.