1

I would like to assign variable (matrices names) dynamically and assigning some values.

Below is the sample code I am trying. The expected output is mat1 and mat2 containing values 1 and 1 respectively.

stri = "mat"

for i in range(1,2):  
     "_".join([stri, i])=1
0

2 Answers 2

7

I would suggest you don't assign actual variables this way. Instead just create a dictionary and put the values in there:

stri = "mat"
data = {}
for i in range(1,2):  
     data["_".join([stri, str(i)])] = 1

If you really want to do that (which I again do absolutely not recommend, because no IDE/person will understand what you are doing and mark every subsequent access as an error and you should generally be very careful with eval):

stri = "mat"

for i in range(1,2):  
     eval(f'{"_".join([stri, i])}=1')
Sign up to request clarification or add additional context in comments.

Comments

0

As noted in RunOrVeith's answer, a Dict is probably the right way to do this in Python. In addition to eval, other (non-recommended) ways to do this including using exec or setting local variables as noted here

stri = "mat"

for i in range(1,3):  
    exec("_".join([stri, str(i)])+'=1')

or locals,

stri = "mat"

for i in range(1,3):  
    locals()["_".join([stri, str(i)])] = 1

This define mat_1 = 1 and mat_2 = 1 as required. Note a few changes to your example (str(i) and range(1,3) needed, for python3 at least).

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.