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
Wrapping Long Y Labels in Matplotlib Tight Layout Using Setp
Subclassing Python Dictionary to Override _Setitem_
What Are All the Dtypes That Pandas Recognizes
How to Convert an Integer to the Shortest Url-Safe String in Python
Pycharm: Set Environment Variable for Run Manage.Py Task
How to Get All the Request Headers in Django
Broken References in Virtualenvs
Django - Makemigrations - No Changes Detected
Get the String Within Brackets in Python
Python Pandas Dataframe, Is It Pass-By-Value or Pass-By-Reference
Cannot Redirect Output When I Run Python Script on Windows Using Just Script's Name
Define CSS Class in Django Forms
Pip Is Not Able to Install Packages Correctly: Permission Denied Error
Binary Numpy Array to List of Integers
How Do Threads Work in Python, and What Are Common Python-Threading Specific Pitfalls
How to Delete Created Variables, Functions, etc from the Memory of the Interpreter