Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
variable_1 = "Dummy String"
variable_2 = "Dummy String"
variable_3 = "Dummy String"

for each in range(3):
    variable_(each+1) = "Another Dummy String"

The above is incorrect syntax for a problem I am trying to solve.

The purpose of this code is to append the numbers 1-3, to the end of the variable name, before modifying the contents of the variable.

On the run through of the loop - for the value 0 - the value 0 + 1 (1) should be appended to 'variable_' yielding variable_1.

My question is: Is this something that is possible in Python? (Python 2.7.8 more specifically), and/or is there a more practical way to achieve a similar result?

share|improve this question

1 Answer 1

usually, you want to use a list instead of a bunch of different similarly named variables:

variables = ['Dummy String'] * 3
for i in range(3):
    variables[i] = 'Another Dummy String'

Have a look at Ned Batchelder's "keep data out of your variable names".

share|improve this answer
    
I don't believe a list will work for what I'm trying to do. variables[i] will access the information stored within a list item, but i'm unable to run methods on each list item as an individual variable. variables[i].configure Vs. variable_1.configure –  Kastoli Sep 16 '14 at 3:00
    
You can use globals()['variable_%d' % i] = 'Another Dummy String' -- But that only works in the global namespace and it really isn't the right way to do it. . . –  mgilson Sep 16 '14 at 3:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.