generate a random array in python

Here are five ways to generate a random array in Python:

Using Python's built-in random module

main.py
import random

arr = [random.randint(1, 100) for _ in range(10)]
65 chars
4 lines

Using numpy

main.py
import numpy as np

arr = np.random.rand(10)
45 chars
4 lines

Using list comprehension and random.sample

main.py
import random

arr = random.sample(range(1, 100), 10)
54 chars
4 lines

Using numpy and reshape

main.py
import numpy as np

arr = np.random.rand(10).reshape((2, 5))
61 chars
4 lines

Using numpy and randint

main.py
import numpy as np

arr = np.random.randint(1, 100, size=10)
61 chars
4 lines

related categories

gistlibby LogSnag