Linked Questions
181 questions linked to/from How can you dynamically create variables?
566 votes
19 answers
282k views
How do I create variable variables?
I know that some other languages, such as PHP, support a concept of "variable variable names" - that is, the contents of a string can be used as part of a variable name. I heard that this is ...
10 votes
2 answers
76k views
Creating dynamically named variables from user input [duplicate]
I'm just learning to program and am learning Python as my first language. As an exercise I'm trying to write an address book program. New contact are created by the user using the command prompt. ...
0 votes
4 answers
4k views
In Python, how to create a large number of variables in a loop? [duplicate]
I'm looking for a way, in python 3.2, to create a large number of variables and assign them values. Something like X = 10 Y = 10 A = 0 B = 0 while X >= 0: while Y >= 0: cell[C]X[A] =...
2 votes
5 answers
13k views
(Python) Creating a list with a unique automatically generated name [duplicate]
I am trying to automate populating a town by randomly generating households. I generate the name of the town, generate the number of households, the last name of each household and number of occupants ...
0 votes
2 answers
18k views
Python create variable according to for loop index [duplicate]
I am trying to create variable for each iteration of the for loop: for i in range(10): x(i) = 'abc' so that I would get x1, x2, x3, x4, .... x10, all equal to 'abc' Anyone know how to do it? Thanks!...
1 vote
6 answers
9k views
Dynamic variable creation [duplicate]
My question is how to create variables "on the fly". I'm trying to generate an object with a random set of attributes. from random import randint, choice class Person(object): def ...
3 votes
5 answers
6k views
Run a loop to generate variable names in Python [duplicate]
I'm trying to import datasets which have the following filenames (phone1, phone2, etc) df1 = pd.read_csv(r'C:\Users\...\phone1.csv') df2 = pd.read_csv(r'C:\Users\...\phone2.csv') df3 = pd.read_csv(r'C:...
1 vote
2 answers
19k views
PYTHON - creating multiple lists in a loop [duplicate]
I'm trying to put together a programming project at my university, but I'm stuck. The "math" part I've got covered, but I need help with lists and loops in Python. I'm working with graphs, let me ...
0 votes
1 answer
13k views
Pandas: Dictionary of Dataframes [duplicate]
I have a function that I made to analyze experimental data (all individual .txt files) This function outputs a dictionary ({}) of Pandas Dataframes Is there a efficient way to iterate over this ...
2 votes
2 answers
6k views
String Variables to Variable Name? [duplicate]
I was just wondering if there was a way I could create variables from string like in the code below, I can create a file which includes the variable subject in the filename. filehandle = open('...
-1 votes
2 answers
8k views
defining variable names with integer values defined by user in python [duplicate]
I am currently trying to write a simple program to calculate probabilities of possible combinations with dice of different sizes (e.g. : 6, 12, 4, 20). The problem i have is that it is supposed to be ...
0 votes
3 answers
7k views
dynamically creating variables in python [duplicate]
I have a file that stores variable names and values like below: name,David age,16 score,91.2 ... I want to write a python script that reads the file and automatically creates variables in an object ...
3 votes
2 answers
3k views
Instantiate a class using a variable for its name [duplicate]
I'm a little new to Python, and was hoping that someone might be able to help me with a problem I've got. I have the need to instantiate multiple objects using the variables in a list. Let's say I ...
0 votes
5 answers
2k views
Python name variable from string [duplicate]
Is it possible to create a variable name based on the value of a string? I have a script that will read a file for blocks of information and store them in a dictionary. Each block's dictionary will ...
0 votes
1 answer
3k views
Invalid syntax using np.zeros [duplicate]
I would like to write this: x = 'something_{}'.format(1) exec('{} = {}'.format(x,np.zeros((2,2)))) Problem: I get SyntaxError: invalid syntax and I don't know how to solve it. Someone has an idea?
1 vote
2 answers
1k views
Rename dataframe object [duplicate]
I have a list files that I want to iterate over and import as dataframes: data_files = ['data1.csv', 'data2.csv', 'data3.csv'] I'm trying to iterate over the list and create eponymously name ...
1 vote
1 answer
2k views
defining variable names with counters in python [duplicate]
I am trying to assign every letter in the given word 'cmpny' to an undefined variable(here, i am using counters as variable) var_counter = 0 user_input = 'cmpny' for usr in user_input: ...
1 vote
1 answer
2k views
Using the index of a for loop to name new objects inside the loop [duplicate]
I want to run a for loop with index i so that I can define (inside each loop) an ndarray with name A_i. More concretely, I want it to look something like for i in range(numer): A_i = M where M is ...
-2 votes
2 answers
948 views
Cycle through letters of the alphabet in a loop and assign values to them in Python? [duplicate]
Here the number of variables (which correspond to numfactors) are assigned manually to each letter of the alphabet. So the first variable is A and it gets assigned the value of an array slice (paths[...
-3 votes
3 answers
206 views
Dynamically define variable names [duplicate]
I have written some classes I would like to test by creating multiple instances of my classes. I would like those instances to have names following the pattern p1, p2, etc: p1 = Point(1,1) p2 = Point(...
0 votes
0 answers
1k views
How to include variable in another variable name? [duplicate]
I have a simple problem in python. I am trying to create a varible which uses the value of another variable in its name. A pertinent part of the code is: for m in range (1,4): if m ==1: ...
3 votes
1 answer
2k views
Python: change class instance name - create class instance through function [duplicate]
I have a class for which I want to create instances through a function, but I also want to be able to name the instances with the value of a Tkinter.Entry widget. The simplified version of that I am ...
-1 votes
1 answer
1k views
How do I add for loop counter number as part of variable name in Python? [duplicate]
Based on the code below, I am trying to create a for loop that has a variable in it but the variable name changes based on counter number. What should I do? I want the final product of this for loop ...
-1 votes
2 answers
568 views
Can I change the name of a variable depending on another variable? [duplicate]
I want to change a variable using another variable without doing the boring old way of: if choice == 'tuna': tuna_num -= 1 Instead I wanted to do it in a just as quick way as the method seen below: ...
2 votes
2 answers
107 views
Changing value of a python variable whose name is in a string [duplicate]
Before you say to use a dictionary, I want to change the value of the actual variable. This is what happens with the standard dict strategy: (Note that I'm not necessarily using a list, the value ...
-2 votes
4 answers
303 views
Dynamic Python Variables [duplicate]
I have a simple question: I have this code: # open an HTML file on my own (Windows) computer url = "$user data here" webbrowser.open(url,new=new) I need to have it so that when it is run the user ...
1 vote
4 answers
125 views
How to use forloop for variable names [duplicate]
I have variables text1, text2, text3. I want to print them. for i in range(1, 4): text = 'text' + str(i) print(text) This code prints strings text1 text2 text3 , not the content of them.
0 votes
1 answer
395 views
How to convert each item of a list of strings into an empty list object with the string as list name? [duplicate]
I would like to convert each item of a list of strings into an empty list object with the string as list name. Input: list_items = ["string1","string2"] Output: 2 empty lists ...
1 vote
0 answers
357 views
How to automatically create x amount of variables in Python? [duplicate]
I'm making a piece of code that asks users to input their name and three scores into a program. This will continue happening within a while loop until it is stopped (meaning there could be 2 users ...
0 votes
1 answer
354 views
Create list name dynamically? [duplicate]
Let's say I have multiple lists called level_1, level_2, level_3.. Now I want to loop through all of them, but want to use list 1 on idx 1, list 2 on idx 2, .. My solution would be something like this:...
1 vote
3 answers
65 views
Python: Use a variable when calling a definition [duplicate]
I'm currently making a game for CompSci class, and I want to shorten our random monster fights. Is there a way to make it so when I call a def I can change the name depending on a random variable? ...
-4 votes
2 answers
223 views
Python - Dynamically naming variables [duplicate]
I have a function in which variables of 'node1', 'node2', 'node3' are referenced. I would like to make it so that the second time the function is called, 'node1' become 'node1_a' and on the third ...
0 votes
2 answers
166 views
Calling data from a dictionary created in a for loop in python [duplicate]
I am having some problems retrieving data from a dictionary that is created in a for loop. In my code I have two dictionaries created and updated periodically, one from a machine database and one from ...
0 votes
1 answer
203 views
Python 2.7: set variable name [duplicate]
I would like to set the variable name in a for loop, like: for i in range(5): namei = i # this is a variable name It will give me: name0 = 0 name1 = 1 name2 = 2 name3 = 3 name4 = 4 does anyone ...
-4 votes
1 answer
108 views
How can I make my program create variables automatically and print them by it self? [duplicate]
I've got an idea for a program that I'm not sure how to implement. How can I make the program ask the user something -- input() -- as many times as user responds until x command is written and (and ...
0 votes
4 answers
138 views
How to connect strings in a list to the object to which the string refers [duplicate]
I'm having an absolute mind-block. This is my data: db_one = 1 db_two = 2 db_three = 3 db_four = 4 list_to_iterate = ['one','two','three','four'] for each_item in list_to_iterate: new_string = '...
0 votes
0 answers
133 views
Creating objects in a loop in Python [duplicate]
this is my first post so I am sorry if I get any formatting wrong. I have searched this before in stackoverflow and it did come up with a few responses but I didn't really understand as I couldn't ...
-3 votes
6 answers
130 views
Is is possible to join a variable and a number to make a new variable? [duplicate]
I am using Python 2.5. In the code below want to print either err1, err2 or err3 depending on the value of x. Is it possible to create the variables err1, err2 or err3 by joining "err" plus the value ...
0 votes
0 answers
119 views
Naming variable inside a for loop in python [duplicate]
I want to create 6 pandas dataframes from 6 text files. I want to name them according to the names of the text files. The text files are named as 'DAPC_min.txt' and so on. I want the dataframe names ...
0 votes
1 answer
70 views
Create a Class object using the username from incoming data [duplicate]
Python newbie here: I have a class ExampleState: ... My purpose is to create a class object unique to every user. I get the username from my client flutter app in django. So, instead of state = ...
0 votes
2 answers
91 views
Dynamically creating variables by need in python [duplicate]
I have a list of IDs I'm trying to manipulate in order to get long strings of the following format: "ID1,ID2,ID3,....,IDn". that is, a long string where the IDs are separated by commas, which are ...
0 votes
2 answers
62 views
How can I refer to a variable from a string? [duplicate]
I'm coding a text-based adventure game for my python project in school, and I'm currently creating a fight function. It involves a lot of dictionaries, hence why I need to refer to a variable from a ...
-2 votes
1 answer
63 views
Python - Is it possible to refer to multiple different variables using different variable? [duplicate]
Sorry if the title is confusing but I couldn't think of a better way to word it. I'm making a game with a friendship system and this is essentially what I'm trying to do: playerChar = "Adam";...
0 votes
1 answer
91 views
How do I create a different variable name inside a loop? [duplicate]
Here is the code to start with. Ignoring all the CSV jazz if you want, the important part is the loop. import csv Teacher_Array = [] class Teacher: def __init__ (self, login, password, name, ...
0 votes
1 answer
41 views
List of strings. New variables with those name (without classes). Python [duplicate]
if one had a list of strings, how could they create variables (empty list objects) with those names? pre_vars= ['list_1','list_2','list_3'] print list_1,list_2,list_3 >>> [],[],[] I saw ...
0 votes
0 answers
74 views
create a list of objects from a list of names [duplicate]
This is the original code: class stock(object): def __init__(self,ticker): self.ticker = ticker tickers = ['KO','JNJ','PFE','NKE','PG','WMT','MMM','IBM'] stocks = [] leng = len(tickers) for i in ...
0 votes
1 answer
58 views
python Fetch existing variables into a list [duplicate]
I've used locals() function and created some variables. Now I need to fetch all the variables created into a list, how should I do? example: column_list=[x for x in range(100)] for i,j in enumerate(...
-1 votes
5 answers
65 views
Print a variable inside a variable [duplicate]
line0 = "hello" line1 = "stack" line2 = "overflow" linenum = 1 for x in range(3): linenum = "line%d"%(x) print(linenum) I would like to print hello ...
0 votes
2 answers
38 views
Calling a variable the value of another variable [duplicate]
I'm creating a loop which looks a it like this players = int(input('How many players? ')) for i in range (0,players): name = input('What is your name? ') Then I want the next variable to be '...
-1 votes
2 answers
131 views
Access dynamic named variables inside a loop [duplicate]
I'm trying to create a lot of variables inside a loop. for i in range(10): globals()[f"variables{i}"] = i perfect, so now I have variables0 = 0, variables1 = 1, variables2 = 2, etc. But ...