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

2

2 Answers 2

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.

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

2 Comments

It is only concatenation. i want to use this(serial_5,serial_6...) as variable name.
well this will work but i also want to know is there other way to do this without dict. like a simple variable (serial_0 =5)
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}

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.