Python Forum
Generate a list of numbers within a list of arbitrary numbers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Generate a list of numbers within a list of arbitrary numbers (/thread-13939.html)



Generate a list of numbers within a list of arbitrary numbers - Takeshio - Nov-07-2018

Hi Guys,

Suppose I have a list of arbitrary numbers (23, 2, 49, 100, 101) and from this list, I want to randomly pick 3 unique numbers and store them inside a new list. I can’t use random.sample() function, as the function will generate the numbers based on a range of sequence numbers.

Can you please advise me on how to pick 3 unique numbers from a list of arbitrary numbers, and store them in a new list?

Thank you.


RE: Generate a list of numbers within a list of arbitrary numbers - buran - Nov-07-2018

I don't understand what the problem with using random.sample() is
from random import sample

population = (23, 2, 49, 100, 101)
my_sample = sample(population, 3)
print(my_sample)
Output:
[101, 100, 49] >>>



RE: Generate a list of numbers within a list of arbitrary numbers - Takeshio - Nov-07-2018

(Nov-07-2018, 12:30 PM)buran Wrote: I don't understand what the problem with using random.sample() is
from random import sample

population = (23, 2, 49, 100, 101)
my_sample = sample(population, 3)
print(my_sample)
Output:
[101, 100, 49] >>>

Thanks Buran. Maybe I misunderstood that random.sample() will need to specify “range” of sequence numbers as its parameter, in order for it to work.

Once again, thank you for your help.


RE: Generate a list of numbers within a list of arbitrary numbers - buran - Nov-07-2018

I think you were just confused by the example with range.
Note that if you have repeated numbers in the original list it's also possible to have repeating elements in the sample


RE: Generate a list of numbers within a list of arbitrary numbers - Takeshio - Nov-08-2018

(Nov-07-2018, 02:36 PM)buran Wrote: I think you were just confused by the example with range.
Note that if you have repeated numbers in the original list it's also possible to have repeating elements in the sample

Yup. Understand that repeated numbers may be picked up if there are duplicates in the population list.

Thanks Buran.