0

I require to create a list of numpy arrays with zeros to accomplish something as follows.

import numpy as np
a = np.zeros([10,1])
b = np.zeros([10,1])
c = np.zeros([10,1])
d = np.zeros([10,1])
e = np.zeros([10,1])

Therefore, I created a list of variable names and ran a for loop as follows

list = ['a', 'b' , 'c', 'd' , 'e']
for i in list:
    i = np.zeros([10,1])

I know I am wrong or missing something while doing the above steps. Can someone tell me what's the mistake and a proper way to do it?

1
  • You are assigning array to a string instead of variable. Commented Sep 18, 2018 at 12:06

3 Answers 3

2

Best way is to use dictionary:

list = ['a', 'b' , 'c', 'd' , 'e']
mydict = {}
for i in list:
    mydict[i] = np.zeros([10,1])



>>>mydict['a']
array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]])   

With your previous statement : i = np.zeros([10,1]) , you were just reassigning value of i to the numpy array and not actually assigning the array to the "variable", like below :

list = ['a', 'b' , 'c', 'd' , 'e']
mydict = {}
for i in list:
    i= np.zeros([10,1])
print i 


[[ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]
 [ 0.]]
Sign up to request clarification or add additional context in comments.

Comments

1

Would you be fine with using a dictionnary?

Dict = {}

list = ['a', 'b' , 'c', 'd' , 'e']
    for i in list:
       Dict[i] = np.zeros([10,1])

The various i are you dictionnary keys now, so after the for loop you can retrieve the desired array using a = Dict["a"]. I'm sure there is a more elegant solution though.

Comments

0

you can use following code that init it in inline dictionary

  mydict = { i:np.zeros([10,1]) for i in ['a', 'b' , 'c', 'd' , 'e']  }

    print(mydict['a'])

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.