0

In Python, I want to be able to create a new variable with a name close to another one in a loop at a certain runtime event an example

for i in range (100):
   ###create a variable called var"i" = i

so after running the loop i would have a 100 new variables where
var1 = 1
var2 = 2
var3 = 3
...

or maybe at certain event (lets say maybe a button pushed) a NEW string containing some info (say the contents of a QLineEdit text box) called stringX so it doesn't overwrite the previous one

I searched around a little bit found "exec" but I would like some more explanation and to see if there is a way to do it without using "exec"

2
  • This doesn't make a lot of sense. Why do you need separate variable names? It sounds like you probably want to use an actual data structure, like a list or a dict instead. Commented Jun 17, 2013 at 14:24
  • Thanx this will probably solve my problem , I am very new to programming (and self-taught :D) still have got into the the "mind-frame of thr programmer" Commented Jun 17, 2013 at 14:33

1 Answer 1

1

To store a sequence of values in Python, use a list. To initialize the list with a for loop, you have to initialize the variable to be an empty list:

sequence = []
for i in range(1, 101):
    sequence.append(i**2)
print(sequence)

will print the list [1, 4, 9, 16, ..., 10000].

This is essentially a sequence of 100 variables: sequence[0], sequence[1], etc.

Also note that range(1, 101) itself produces a list-like generator.

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

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.