I would advise against using eval in 99.99% of all cases. What you could do is use the built-in getattr function:

import sys
var_1 = 10
var_2 = 100
var_3 = 1000

for i in range(1,4):
    test_i = getattr(sys.modules[__name__], f"var_{i}") + 1
    print(test_i)
Answer from Alexander Ejbekov on Stack Overflow
Top answer
1 of 3
3

I would advise against using eval in 99.99% of all cases. What you could do is use the built-in getattr function:

import sys
var_1 = 10
var_2 = 100
var_3 = 1000

for i in range(1,4):
    test_i = getattr(sys.modules[__name__], f"var_{i}") + 1
    print(test_i)
2 of 3
2

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.

🌐
SPSS Tutorials
spss-tutorials.com › suffix-all-variable-names
How To Suffix All Variable Names?
I'd like to suffix their names with "_2012". What's the easiest way to do this?” · begin program. variables = 'v5 to v10' #Specify variables to be suffixed. suffix ='_2012' # Specify suffix. import spss,spssaux oldnames = spssaux.VariableDict().expand(variables) newnames = [varnam + suffix for varnam in oldnames] spss.Submit('rename variables (%s=%s).'%('\n'.join(oldnames),'\n'.join(newnames))) end program. This syntax will add a suffix to one, many or all variables in your data.
Discussions

How do I add a prefix/suffix to any given string in python? - Stack Overflow
"Your task is to write a function that adds a prefix or suffix to a person's name. The name of your function should match exactly as shown below, including cases (all lowercase") def fix... More on stackoverflow.com
🌐 stackoverflow.com
python - How do I add a suffix to the end of each list element? - Stack Overflow
I have two, unequal length lists. The first list contains variable names for a longitudinal study, the other contains suffixes for these variables. The user supplies a CSV from which the variable n... More on stackoverflow.com
🌐 stackoverflow.com
python - Add comma with Variable name as suffix - Stack Overflow
I am almost there but finding it hard to append comma (,) in a for loop along with variable name as suffix (i.e. line 6in the below code series.add_suffix(', Temp9am') where var is the variable name from for loop and I need , in front of it. More on stackoverflow.com
🌐 stackoverflow.com
December 29, 2020
How to add prefix and suffix to a string in python - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
🌐
Program Creek
programcreek.com › python
Python add suffix
def add_suffix(name, suffix): """A function that adds suffix to a variable.
🌐
Python
peps.python.org › pep-0008
PEP 8 – Style Guide for Python Code | peps.python.org
Names of type variables introduced in PEP 484 should normally use CapWords preferring short names: T, AnyStr, Num. It is recommended to add suffixes _co or _contra to the variables used to declare covariant or contravariant behavior correspondingly:
🌐
OARC Stats
stats.oarc.ucla.edu › spss › faq › how-can-i-write-a-python-program-to-rename-variables-in-spss
How can I write a Python program to rename variables in SPSS? | SPSS FAQ
As before, we use the spssaux.VariableDict() function to obtain the names of the variables in the data file, then we select only the variables between the start variable and the end variable, and put those names into a Python variable called mylist. The loop used in this example is almost identical to the loop used in the previous example. Finally, we use our new function and then end the program. def renamefun(datapath, mystart, myend, suffix): spssaux.OpenDataFile(datapath) vdict=spssaux.VariableDict() mylist=vdict.range(start=mystart, end=myend) nvars = len(mylist) for i in range(nvars): myvar = mylist[i] mynewvar = myvar+suffix spss.Submit(r""" rename variables ( %s = %s) .
🌐
W3Schools
w3schools.com › python › pandas › ref_df_add_suffix.asp
Pandas DataFrame add_suffix() Method
HTML Reference CSS Reference JavaScript Reference SQL Reference Python Reference W3.CSS Reference Bootstrap Reference PHP Reference HTML Colors Java Reference AngularJS Reference jQuery Reference · HTML Examples CSS Examples JavaScript Examples How To Examples SQL Examples Python Examples W3.CSS Examples Bootstrap Examples PHP Examples Java Examples XML Examples jQuery Examples
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 65490730 › add-comma-with-variable-name-as-suffix
python - Add comma with Variable name as suffix - Stack Overflow
December 29, 2020 - df_sorted_ corre_score = pd.DataFrame() for var in df_sorted_.columns: series = df_sorted_[var] series_ = series.add_suffix(', var') series1 = pd.DataFrame(series_) series1.columns = ['Score_'] series1 ... Do you not need to use var as var and not as string? I am not quite sure if that's your problem, but it's something I spotted. series.add_suffix(',' + var) maybe?
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-append-suffix-prefix-to-strings-in-list
Python | Append suffix/prefix to strings in list - GeeksforGeeks
May 3, 2023 - This is because we create two lists of size n to store the results of the prefix and suffix addition · Method #6: Using the reduce() function from the functools module ... Import the reduce() function from the functools module. Create a test_list of strings. Create two variables prefix and suffix with the desired string values.
🌐
GeeksforGeeks
geeksforgeeks.org › python › changing-variable-names-with-python-for-loops
Changing Variable Names With Python For Loops - GeeksforGeeks
July 23, 2025 - It utilizes a for loop to iterate through the original names, creates new names with the suffix, and appends them to the list suffixed_names. Python3 · # Adding Suffix to Variable Names original_names = ["x", "y", "z"] suffixed_names = [] for name in original_names: suffixed_name = name + "_new" suffixed_names.append(suffixed_name) print("Original Names:", original_names) print("Suffixed Names:", suffixed_names) Output ·
🌐
IBM
ibm.com › mysupport › s › question › 0D50z00006PsF4mCAF › dynamically-renaming-long-arrays-of-variable-names-by-turning-suffixes-into-prefixes
Ibm
April 16, 2020 - Loading · ×Sorry to interrupt · Refresh · Skip to main content · Open a case · Still have questions · Reach out to us directly · View global contactsGet help · Report a problem submitting a case or registering for support
🌐
Google Groups
groups.google.com › g › comp.soft-sys.stat.spss › c › VfYQFDkcoDs
Add a suffix to all variable names
January 24, 2007 - The next line creates a list of the new names. Then the Submit line executes a RENAME VARIABLES command using the two lists. This approach generalizes to selecting the variables to operate on using a TO-like range, variable type or other selection mechanisms. If you change the varlist = line, for example, to this, you have the equivalent of x TO y. varlist = spssaux.VariableDict().range("x", "y") ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
🌐
w3resource
w3resource.com › pandas › series › series-add_suffix.php
Pandas Series: add_suffix() function - w3resource
September 15, 2022 - Pandas Series - add_suffix() function: The add_suffix() function is used to suffix labels with string suffix.
🌐
Stack Overflow
stackoverflow.com › questions › 74535563 › add-suffix-to-variable
Add suffix to variable - Stack Overflow
I want to add the string MN to the year 2021, assigned to Targetyear. %put &Targetyear1_MN; This one works: %put MN_&Targetyear1; How can I add the MN at then end? Thanks. Kind regards, Ben