Changing Variable Names with Python for Loops

Python: Change variable suffix with for loop

Instead of doing a convoluted naming convention, try to conceive of your problem using a data structure like dictionaries, for example.

var={}
var[1] = 10
var[2] = 100
var[3] = 1000

test={}
for i in range(1,4):
test[i] = var[i] +1

print(test)

If somehow you are given var_1 etc as input, maybe use .split("_") to retrieve the index number and use that as the dictionary keys (they can be strings or values).


Small explanation about using indexing variable names. If you are starting out learning to program, there are many reasons not to use the eval, exec, or getattr methods. Most simply, it is inefficient, not scalable, and is extremely hard to use anywhere else in the script.

I am not one to insist on "best practices" if there is an easier way to do something, but this is something you will want to learn to avoid. We write programs to avoid having to type things like this.

If you are given that var_2 text as a starting point, then I would use string parsing tools to split and convert the string to values and variable names.

By using a dictionary, you can have 1000 non-consecutive variables and simply loop through them or assign new associations. If you are doing an experiment, for example, and call your values tree_1, tree_10 etc, then you will always be stuck typing out the full variable names in your code rather than simply looping through all the entries in a container called tree.

This is a little related to using a bunch of if:else statements to assign values:

# inefficient way -- avoid
if name == 'var_1' then:
test_1=11
elif name == 'var_2' then:
test_2=101

It is so much easier just to say:

test[i]= var[i]+1

and that one line will work for any number of values.

How do you create different variable names while in a loop?

Sure you can; it's called a dictionary:

d = {}
for x in range(1, 10):
d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}

I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!

How to rename variables in a loop in Python

Using a dict:

arraysDict = {}
for i in range(0,3):
arraysDict['x{0}'.format(i)] = [1,2,3]

print arraysDict
# {'x2': [1, 2, 3], 'x0': [1, 2, 3], 'x1': [1, 2, 3]}
print arraysDict['x1']
# [1,2,3]

Using a list:

arraysList = []
for i in range(0,3):
arraysList.append([1,2,3])

print arraysList
# [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
print arraysList[1]
# [1, 2, 3]

how to change the name of a variable in a loop using python

I highly recommend using a dict() or a list(), but what you're trying to do is fairly simple:

for i in range(whatever):
locals()[f'x{i+1}'] = np.array([i, i, i])





Dictionary:

d = {f'x{i+1}':np.array([i, i, i]) for i in range(whatever)}

How to create variable names with a for loop?

Creating variables dynamically is an anti-pattern and should be avoided. What you need is actually a list:

total_squares = 8
box_list = []
boxes = [0] * total_squares
for q in range(total_squares):
box_list.append(boxes[q])

Then you can refer to any element you want (say, box_i) using the following syntax:

my_box = box_list[boxes[i]]


Related Topics



Leave a reply



Submit