1

Is there anyway to assign value in concatenated variable?

I want to concatenate and assign a value in it.

for i in range (5):
    'serial_' + str(i) = i+5

that showing SyntaxError: can't assign to operator

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
Chandan Kumar
  • 128
  • 1
  • 9

2 Answers2

1

If I understand correctly,

d = {}
In [898]: for i in range (5):
     ...:    d[ ('{}' + str(i)).format('serial_')] = i+5


In [899]: d
Out[899]: {'serial_0': 5, 'serial_1': 6, 'serial_2': 7, 'serial_3': 8, 'serial_4': 9}

Let me know if this is what you want.

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
0

It is possible to add variables with concatenated names in the global/local symbol table using the globals and locals built-in functions:

>>> for i in range (5):
...     global()['serial_' + str(i)] = i+5
... 
>>> serial_0
5
>>> serial_3
8

However according to the documentation, changing the dictionary returned by locals may have no effect to the values of local variables used by the interpreter.

Furthermore since modifying the global symbol table is not considered a good practice, I recommend you to use a dictionary to store your values as suggested by Mayank Porwal as this will result in cleaner code:

>>> d = {f'serial_{i}' : i + 5 for i in range(5)}
>>> d
{'serial_0': 5, 'serial_1': 6, 'serial_2': 7, 'serial_3': 8, 'serial_4': 9}
kalehmann
  • 4,821
  • 6
  • 26
  • 36