Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Random numbers into a list

Create a 'list' called my_randoms of 10 random numbers between 0 and 100.

This is what I have so far:

import random my_randoms=[] for i in range (10):     my_randoms.append(random.randrange(1, 101, 1))     print (my_randoms) 

Unfortunately Python's output is this:

[34] [34, 30] [34, 30, 75] [34, 30, 75, 27] [34, 30, 75, 27, 8] [34, 30, 75, 27, 8, 58] [34, 30, 75, 27, 8, 58, 10] [34, 30, 75, 27, 8, 58, 10, 1] [34, 30, 75, 27, 8, 58, 10, 1, 59] [34, 30, 75, 27, 8, 58, 10, 1, 59, 25] 

It generates the 10 numbers like I ask it to, but it generates it one at a time. What am I doing wrong?

like image 966
Linda Leang Avatar asked May 20 '13 17:05

Linda Leang


People also ask

How do you generate random 50 numbers in Python?

The randint() method to generates a whole number (integer). You can use randint(0,50) to generate a random number between 0 and 50. To generate random integers between 0 and 9, you can use the function randrange(min,max) .

How do you generate an array of random numbers in Python?

An array of random integers can be generated using the randint() NumPy function. This function takes three arguments, the lower end of the range, the upper end of the range, and the number of integer values to generate or the size of the array.

How do you select multiple random values in a list Python?

Use the numpy. random. choice() function to pick multiple random rows from the multidimensional array.


2 Answers

import random my_randoms = [random.randrange(1, 101, 1) for _ in range(10)] 
like image 38
mattexx Avatar answered Sep 17 '22 00:09

mattexx


You could use random.sample to generate the list with one call:

import random my_randoms = random.sample(range(100), 10) 

That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution):

my_randoms = random.sample(range(1, 101), 10) 
like image 58
robertklep Avatar answered Sep 18 '22 00:09

robertklep