user42298
user42298

Reputation: 1911

how to increase variable name in Python?

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

Upvotes: 0

Views: 2350

Answers (4)

David Frye
David Frye

Reputation: 498

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)

Upvotes: 0

gaj
gaj

Reputation: 327

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)

Upvotes: 0

Abhijit
Abhijit

Reputation: 63727

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]}

Upvotes: 5

Andrew Johnson
Andrew Johnson

Reputation: 3186

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)] )

Upvotes: 1

Related Questions