I am new to Python but I have a decent amount of experience in Java and C, I am trying to create an array of a certain size then fill it with random numbers but no python tutorials about arrays mention methods about doing this (if I search explicitly about wanting that I get results that is not the problem) so I was wondering if that is considered a bad practice in Python and there are alternative ways to accomplishing what I want. Thank you.
4 Answers
Still to new to comment on @icejoywoo post ^
list are basically arrays for most purposes.
list comprehension is the easiest way to fill an array with lots of things
[ returnVal for i in range(10)]
any for loop or iterator will work return value itself can be a function
x= [None for i in range(10)]
[None,None..None]
x= [x**2 for i in range(10)]
[0,1,4..81]
y = lambda a: int((a**.5)*100)
x= [y(i) for i in range(10)]
[0, 100, 141, 173, 200, 223, 244, 264, 282, 300]
Comments
use random or numpy
In [1]: import random
In [2]: [random.random() for i in range(10)]
Out[2]:
[0.8233249954348517,
0.6215056571076538,
0.6273288221606772,
0.12055176228045617,
0.22782244162965615,
0.9016145766629989,
0.04615407289582629,
0.8870216740449745,
0.5622680783939463,
0.9288600326401598]
In [3]: import numpy
In [4]: numpy.random.rand(5)
Out[4]: array([0.9288893 , 0.66600315, 0.82989425, 0.15717061, 0.33444802])
In [5]: list(numpy.random.rand(5))
Out[5]:
[0.46571036413626277,
0.8268980751228664,
0.9216520894106733,
0.26706936577849916,
0.47348417257319697]
Comments
Generally, numpy is the memory efficient and fastest way to work with arrays, especially when doing more complex things.
You can generate n random numbers like so
import numpy as np
# how many random numbers you want
n = 10
# create your array
array = np.random.rand(n)
You can also use a list comprehension to natively create lists, sets, dicts, etc in one beautiful Pythonic line. See section 5.1.3 of the docs
This is often the go to thing and you will be using these a lot.
For your example we can also use Python’s built on random package
import random
# range here is a generator for values 0 to n-1
# array is created by a list comprehension
array = [random.random() for i in range(n)]
listis a general purpose array-like structure that can hold many kinds of objects - numbers, strings, other lists.numpyarrays are more specialized, best for holding numbers in multidimensions.