1

I want to create a np.array filled with lists. The array I want to create is a 2D one. I wonder if there is a way to create this array full of lists kind of like np.zeros((10, 10)) but lists instead of zeros

0

3 Answers 3

2

if you wish to use a list of lists:

import numpy as np
l = [[1,2,3],[2,3,4],[3,4,5]]
np.array(l)
# array([[1, 2, 3],
#        [2, 3, 4],
#        [3, 4, 5]])

if you have multiple list of same dimension:

import numpy as np
l1 = [1,2,3]
l2 = [2,3,4]
l3 = [3,4,5]
np.array([l1, l2, l3])
# array([[1, 2, 3],
#        [2, 3, 4],
#        [3, 4, 5]])
Sign up to request clarification or add additional context in comments.

2 Comments

thanks I tried your way but like array = np.array([[[0, 0, 0] for k in range(10)] for j in range(10)]]) an it works
@Alex I see, happy to help.
0

You can try the following method np.array()

Where you can fill each list with numbers, just make sure that each list(list 1, list 2 ... ) all contain the same number of elements.

arr = np.array([[list 1],
                [list 2],
                [list 3],
                 ...
                [list n]])

2 Comments

Note that this method will create an array of shape (n,1,n) and not (n,n) because you wrap each list in a new list which it's interpreted as another dimension
i meant [list 1] can be [1,2,3,4,5]
0

if you want to generate a random array of lists then you can use np.random.random

>>np.random.random((5,5))
array([[0.72158455, 0.09803052, 0.1160546 , 0.55904644, 0.79821847],
       [0.36929337, 0.15455486, 0.25862476, 0.44324732, 0.06120428],
       [0.95063129, 0.38533428, 0.96552669, 0.07803165, 0.46604093],
       [0.04999251, 0.8845952 , 0.8090841 , 0.64154241, 0.95548603],
       [0.83991298, 0.85053047, 0.36522791, 0.89616194, 0.10960277]])

or to generate random values between a range you can use np.random.uniform

>>np.random.uniform(low=0,high=10,size=(5,5))
array([[4.9572961 , 5.44408409, 6.74143596, 6.57745607, 5.90485241],
       [7.37032096, 0.70533052, 2.93912528, 8.54091449, 7.6188883 ],
       [8.27882354, 0.02749772, 6.45388547, 4.94197824, 9.29715119],
       [6.72579011, 4.65019332, 4.67693981, 2.52006744, 8.3876697 ],
       [8.99122563, 3.70552959, 2.50082311, 8.68846022, 6.34887673]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.