I want to use a for loop to dynamically name variables, assign the variables a value, and then add the variables to a list.
This is Tadeck's answer on how to dynamically create variables in a for loop from How do you create different variable names while in a loop?:
for x in range(0, 9):
globals()['string%s' % x] = 'Hello'
print(string3)
# Output: 'Hello'
Since I also want to add the variables to a list, I tried:
lst = []
for x in range(0, 9):
lst.append(globals()['string%s' % x] = 'Hello')
print(lst)
# Output: SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
# DESIRED OUTPUT: [string0, string1, string2, string3, string4, string5, string6, string7, string8]
I understand what the error message says, but I don't know how to get around it and get the desired output.
Thanks!
globals()
returns you a dict which contains all the variables, defined in current namespace (docs).
To understand better, you can modify the code as follows:
namespace_variables_dict = globals()
for x in range(0, 9):
variable_name = 'string%s' % x
namespace_variables_dict[variable_name] = 'Hello'
print(string3)
And add the names of new variables to the list:
lst = []
namespace_variables_dict = globals()
for x in range(0, 9):
variable_name = 'string%s' % x
namespace_variables_dict[variable_name] = 'Hello'
lst.append(variable_name)
print(lst) # ['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8']