Define variables by iteration

Solved
Brocket -  
yg_be Posted messages 23437 Registration date   Status Contributeur Last intervention   -

Hello,

I would like to know if it would be possible to define variables iteratively.

Let's imagine that I want to create the following variables:

v1 = 1

v2 = 2

v3 = 3

...

v100 = 100

Since I don't want to write the same thing 100 times, I would like to create a loop like this:

for i in range(1,101):

     v+str(i) = i

Of course, that doesn't work. Does anyone have a solution?

Thank you

3 réponses

yg_be Posted messages 23437 Registration date   Status Contributeur Last intervention   Ambassadeur 1 587
 

Hello,

It's possible to do that. However, I think it's a very bad idea, and so I'm hesitant to explain to you how to do it.

Why don't you use a single variable, which would be an array where you could store multiple values?

2
yg_be Posted messages 23437 Registration date   Status Contributeur Last intervention   1 587
 

an example:

v={} for i in range(1,11): v[i] = i*2 for w in range(1,11): print(w,v[w]) 
0
PierrotLeFou
 

Another issue, would the program know how many variables are created?
If you need to test your variables, do you want to generate everything automatically?
For example:
if v60 == 310:
    # bla bla bla ...
It still remains just as lengthy to do all these tests by hand.
With arrays, as yg_be mentioned, it is much simpler.

0
PierrotLeFou
 

The point I wanted to emphasize is not that generating variables in series is more or less complicated (it's easily done with exec()).
It's rather the code that will use them. We quickly end up writing a program that generates another program (code generator).
Most of the time, this is not appropriate or justifiable.
It can be justified if we want to write super optimized and fairly large code.

0
yg_be Posted messages 23437 Registration date   Status Contributeur Last intervention   1 587
 

The method I'm thinking of is very simple to use, both for assigning values and for reading or modifying them.

However, I think it's better to structure the data by taking into account best practices.

0