0

I'm making a simulation program.

I manually write some initial conditions of particles with python list before starting program, such as

var1 = [mass_a, velocity_a, velocity_a]
var2 = [mass_b, velocity_b, velocity_b]
...

then how do I change that number in variable in for loop? Something I tried was

for i in range(2):
    print(var+str(i)) 

but they don't work

4 Answers 4

5

Always remember

If you ever have to name variables suffixed by numbers as in your example, you should consider a sequential indexable data structure like array or list. In Python to create a List we do

var = [[mass_a, velocity_a, velocity_a],
       [mass_b, velocity_b, velocity_b]]

If you ever have to name variables with varying suffixes like

var_A=[mass_a, velocity_a, velocity_a]

var_B=[mass_b, velocity_b, velocity_b]

you should consider a non-sequential indexable data structure like hashmap or dictionary. The key of this dictionary should be the varying suffix and the values should be the values assigned to the respective variable In Python to create a dictionary we do

var = {'A':[mass_a, velocity_a, velocity_a],
       'B':[mass_b, velocity_b, velocity_b]}
Sign up to request clarification or add additional context in comments.

Comments

1

Just to be the devil's advocate here, you can make this approach work as below.

for i in range(2):
    print( globals()["var"+str(i+1)] )

Comments

0

You can put your variables in a list and iterate on it like,

var_list = [var_a,var_b...]

for var in var_list:
    print var

Alternatively, you can put the your variables in a dictionary like,

var_dict = {"var_a":var_a,"var_b":var_b,...}

for var in var_dict:
  print var_dict(var)

Comments

0

Could you put your variables var1, var2, ... into a list and iterate through the list, instead of relying upon numbered variable names?

Example:

vars = [var1, var2]

for var in vars:
    do_something(var)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.