Reputation:
In some other programming languages I am used to, there was a way to dynamically create and call variables. How to do this in Python?
For example let's suppose variables called test1; test2 etc. up to test9, and I want to call them like this:
for n in range(1,10):
print concatenate('test', n)
Of course, the function concatenate is the one I am looking for.
What is the command to combine strings, integers and regular expressions in this way?
My example was a bad one, that made some of the answers suggest dictionary, or some other similar methods. It's either I am not too confident with them, or I can't use them in all cases. Here's another example:
Let's suppose we have a table of 4 rows and 4 columns, and the table has some numbers in it. I want to do some special mathematical operations, which has the row number, column number and the variable as inputs, and it outputs another row-column pair for another mathematical operation.
Logic suggests me that te easiest way to do this would be to have 16 variables, having row and column number in their names. And if I could do operations with the names of the variables, and also return the result and call it as another varialbe, the problem would be easy.
What about this context?
Upvotes: 2
Views: 8670
Reputation:
You could use globals
, which returns a dictionary of what is in the global scope:
>>> test1 = 'a'
>>> test2 = 'b'
>>> test3 = 'c'
>>> globals()
{'test1': 'a', 'test3': 'c', 'test2': 'b', '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
>>> for n in range(1, 4):
... print globals()["test" + str(n)] # Dynamically access variables
...
a
b
c
>>> for n in range(1, 4):
... globals()["dynamic" + str(n)] = n # Dynamically create variables
...
>>> dynamic1
1
>>> dynamic2
2
>>> dynamic3
3
>>>
However, I do not recommend that you actually do this. It is ugly, hackish, and really just a bad practice.
It would be much better to do away with your numbered variables and instead use a list, which will automatically number its items by index:
>>> lst = ['a', 'b', 'c']
>>> lst[0] # Equivalent to test1
'a'
>>> lst[1] # Equivalent to test2
'b'
>>> lst[2] # Equivalent to test3
'c'
>>> for i in lst: # You can iterate directly over the list too
... print i
...
a
b
c
>>> lst.append('d') # "Creating" a new object is easy and clean
>>> lst
['a', 'b', 'c', 'd']
>>>
Basically, instead of test1
, test2
, test3
...you now have lst[0]
, lst[1]
, lst[2]
...
Upvotes: 4
Reputation: 6945
Python doesn't do that as well as some languages, I don't think, but they have a couple useful functions. eval()
lets you evaluate a string as if it were a statement or variable, printing out the value of a given statement.
https://docs.python.org/2/library/functions.html#eval
>>> test9 = 5
>>> eval("test9")
5
for n in range(10):
eval("test" + str(n)) # Need to convert ints to strings to make string concatenation work.
If you wanted to assign values to variables, you'd use exec()
.
https://docs.python.org/2/reference/simple_stmts.html#exec
>>> test9 = 6
>>> exec("test9 = 7")
>>> print test9
7
Upvotes: -3
Reputation: 363063
What you think you want is this:
>>> test1 = 'spam'
>>> test2 = 'eggs'
>>> for i in [1, 2]:
... print locals()['test' + str(i)]
...
spam
eggs
But what you really want is this:
>>> values = 'spam', 'eggs'
>>> my_namespace = {'test' + str(i): v for i, v in enumerate(values, 1)}
>>> for k, v in sorted(my_namespace.items()):
... print v
...
spam
eggs
Keep data out of your variable names.
Upvotes: 4