Python: Random numbers into a list

PythonListRandom

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

import random
my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]

Solution 3 - Python

Fix the indentation of the print statement

import random

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

print (my_randoms)

Solution 4 - Python

This is way late but in-case someone finds this helpful.

You could use list comprehension.

rand = [random.randint(0, 100) for x in range(1, 11)]
print(rand)

Output:

[974, 440, 305, 102, 822, 128, 205, 362, 948, 751]

Cheers!

Solution 5 - Python

Here I use the sample method to generate 10 random numbers between 0 and 100.

Note: I'm using Python 3's range function (not xrange).

import random

print(random.sample(range(0, 100), 10))

The output is placed into a list:

[11, 72, 64, 65, 16, 94, 29, 79, 76, 27]

Solution 6 - Python

xrange() will not work for 3.x.

numpy.random.randint().tolist() is a great alternative for integers in a specified interval:

 #[In]:
import numpy as np
np.random.seed(123) #option for reproducibility
np.random.randint(low=0, high=100, size=10).tolist()

#[Out:]

[66, 92, 98, 17, 83, 57, 86, 97, 96, 47]

You also have np.random.uniform() for floats:

#[In]:
np.random.uniform(low=0, high=100, size=10).tolist()

#[Out]:
[69.64691855978616,
28.613933495037948,
22.68514535642031,
55.13147690828912,
71.94689697855631,
42.3106460124461,
98.07641983846155,
68.48297385848633,
48.09319014843609,
39.211751819415056]

Solution 7 - Python

import random

a=[]
n=int(input("Enter number of elements:"))

for j in range(n):
       a.append(random.randint(1,20))

print('Randomised list is: ',a)

Solution 8 - Python

Simple solution:

indices=[]
for i in range(0,10):
  n = random.randint(0,99)
  indices.append(n)

Solution 9 - Python

The one random list generator in the random module not mentioned here is random.choices:

my_randoms = random.choices(range(0, 100), k=10)

It's like random.sample but with replacement. The sequence passed doesn't have to be a range; it doesn't even have to be numbers. The following works just as well:

my_randoms = random.choices(['a','b'], k=10)

If we compare the runtimes, among random list generators, random.choices is the fastest no matter the size of the list to be created. However, for larger lists/arrays, numpy options are much faster. So for example, if you're creating a random list/array to assign to a pandas DataFrame column, then using np.random.randint is the fastest option.

enter image description here

Code used to produce the above plot:

import perfplot
import numpy as np
import random

perfplot.show(
    setup=lambda n: n,
    kernels=[
        lambda n: [random.randint(0, n*2) for x in range(n)],
        lambda n: random.sample(range(0, n*2), k=n), 
        lambda n: [random.randrange(n*2) for i in range(n)],
        lambda n: random.choices(range(0, n*2), k=n), 
        lambda n: np.random.rand(n), 
        lambda n: np.random.randint(0, n*2, size=n),
        lambda n: np.random.choice(np.arange(n*2), size=n),
    ],
    labels=['random_randint', 'random_sample', 'random_randrange', 'random_choices', 
            'np_random_rand', 'np_random_randint', 'np_random_choice'],
    n_range=[2 ** k for k in range(17)],
    equality_check=None,
    xlabel='~n'
)

Solution 10 - Python

my_randoms = [randint(n1,n2) for x in range(listsize)]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLinda LeangView Question on Stackoverflow
Solution 1 - PythonrobertklepView Answer on Stackoverflow
Solution 2 - PythonmattexxView Answer on Stackoverflow
Solution 3 - PythonkarthikrView Answer on Stackoverflow
Solution 4 - PythonBen SolienView Answer on Stackoverflow
Solution 5 - PythonStrykerView Answer on Stackoverflow
Solution 6 - PythonvestlandView Answer on Stackoverflow
Solution 7 - Pythonperwaiz alamView Answer on Stackoverflow
Solution 8 - PythonPobaranchukView Answer on Stackoverflow
Solution 9 - Pythonuser7864386View Answer on Stackoverflow
Solution 10 - PythonsomeguyView Answer on Stackoverflow