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
RunOrVeith
  • 4,487
  • 4
  • 32
  • 50
avinash0513
  • 23
  • 1
  • 4

2 Answers2

6

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, 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')
RunOrVeith
  • 4,487
  • 4
  • 32
  • 50
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).

Ed Smith
  • 12,716
  • 2
  • 43
  • 55