How do I create a variable number of variables?









up vote
237
down vote

favorite
55












How do I accomplish variable variables in Python?



Here is an elaborative manual entry, for instance: Variable variables



I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?










share|improve this question



















  • 19




    it's the maintainance and debugging aspects that cause the horror. Imagine trying to find out where variable 'foo' changed when there's no place in your code where you actually change 'foo'. Imagine further that it's someone else's code that you have to maintain... OK, you can go to your happy place now.
    – glenn jackman
    Sep 3 '09 at 14:28






  • 3




    The need does still arise, though. I used to think I needed to do this sort of thing all the time before I met real programming languages. Great suggestions here for transitioning to a saner mindset.
    – Jenn D.
    Sep 3 '09 at 17:42






  • 16




    This is an excellent question to ask, if for no other reason than to help people learn how to avoid it. :)
    – SunSparc
    Jul 2 '13 at 21:32






  • 2




    A further pitfall that hasn't been mentioned so far is if such a dynamically-created variable has the same name as a variable used in your logic. You essentially open up your software as a hostage to the input it is given.
    – holdenweb
    Dec 19 '14 at 10:50






  • 1




    It's useful in rare places. I need it somewhere in my code, and it wouldn't cause maintenance problems.
    – sudo
    Jun 6 '16 at 18:50














up vote
237
down vote

favorite
55












How do I accomplish variable variables in Python?



Here is an elaborative manual entry, for instance: Variable variables



I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?










share|improve this question



















  • 19




    it's the maintainance and debugging aspects that cause the horror. Imagine trying to find out where variable 'foo' changed when there's no place in your code where you actually change 'foo'. Imagine further that it's someone else's code that you have to maintain... OK, you can go to your happy place now.
    – glenn jackman
    Sep 3 '09 at 14:28






  • 3




    The need does still arise, though. I used to think I needed to do this sort of thing all the time before I met real programming languages. Great suggestions here for transitioning to a saner mindset.
    – Jenn D.
    Sep 3 '09 at 17:42






  • 16




    This is an excellent question to ask, if for no other reason than to help people learn how to avoid it. :)
    – SunSparc
    Jul 2 '13 at 21:32






  • 2




    A further pitfall that hasn't been mentioned so far is if such a dynamically-created variable has the same name as a variable used in your logic. You essentially open up your software as a hostage to the input it is given.
    – holdenweb
    Dec 19 '14 at 10:50






  • 1




    It's useful in rare places. I need it somewhere in my code, and it wouldn't cause maintenance problems.
    – sudo
    Jun 6 '16 at 18:50












up vote
237
down vote

favorite
55









up vote
237
down vote

favorite
55






55





How do I accomplish variable variables in Python?



Here is an elaborative manual entry, for instance: Variable variables



I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?










share|improve this question















How do I accomplish variable variables in Python?



Here is an elaborative manual entry, for instance: Variable variables



I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?







python variable-variables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 '17 at 16:21









Taryn

187k45285349




187k45285349










asked Sep 3 '09 at 12:37







Pyornide














  • 19




    it's the maintainance and debugging aspects that cause the horror. Imagine trying to find out where variable 'foo' changed when there's no place in your code where you actually change 'foo'. Imagine further that it's someone else's code that you have to maintain... OK, you can go to your happy place now.
    – glenn jackman
    Sep 3 '09 at 14:28






  • 3




    The need does still arise, though. I used to think I needed to do this sort of thing all the time before I met real programming languages. Great suggestions here for transitioning to a saner mindset.
    – Jenn D.
    Sep 3 '09 at 17:42






  • 16




    This is an excellent question to ask, if for no other reason than to help people learn how to avoid it. :)
    – SunSparc
    Jul 2 '13 at 21:32






  • 2




    A further pitfall that hasn't been mentioned so far is if such a dynamically-created variable has the same name as a variable used in your logic. You essentially open up your software as a hostage to the input it is given.
    – holdenweb
    Dec 19 '14 at 10:50






  • 1




    It's useful in rare places. I need it somewhere in my code, and it wouldn't cause maintenance problems.
    – sudo
    Jun 6 '16 at 18:50












  • 19




    it's the maintainance and debugging aspects that cause the horror. Imagine trying to find out where variable 'foo' changed when there's no place in your code where you actually change 'foo'. Imagine further that it's someone else's code that you have to maintain... OK, you can go to your happy place now.
    – glenn jackman
    Sep 3 '09 at 14:28






  • 3




    The need does still arise, though. I used to think I needed to do this sort of thing all the time before I met real programming languages. Great suggestions here for transitioning to a saner mindset.
    – Jenn D.
    Sep 3 '09 at 17:42






  • 16




    This is an excellent question to ask, if for no other reason than to help people learn how to avoid it. :)
    – SunSparc
    Jul 2 '13 at 21:32






  • 2




    A further pitfall that hasn't been mentioned so far is if such a dynamically-created variable has the same name as a variable used in your logic. You essentially open up your software as a hostage to the input it is given.
    – holdenweb
    Dec 19 '14 at 10:50






  • 1




    It's useful in rare places. I need it somewhere in my code, and it wouldn't cause maintenance problems.
    – sudo
    Jun 6 '16 at 18:50







19




19




it's the maintainance and debugging aspects that cause the horror. Imagine trying to find out where variable 'foo' changed when there's no place in your code where you actually change 'foo'. Imagine further that it's someone else's code that you have to maintain... OK, you can go to your happy place now.
– glenn jackman
Sep 3 '09 at 14:28




it's the maintainance and debugging aspects that cause the horror. Imagine trying to find out where variable 'foo' changed when there's no place in your code where you actually change 'foo'. Imagine further that it's someone else's code that you have to maintain... OK, you can go to your happy place now.
– glenn jackman
Sep 3 '09 at 14:28




3




3




The need does still arise, though. I used to think I needed to do this sort of thing all the time before I met real programming languages. Great suggestions here for transitioning to a saner mindset.
– Jenn D.
Sep 3 '09 at 17:42




The need does still arise, though. I used to think I needed to do this sort of thing all the time before I met real programming languages. Great suggestions here for transitioning to a saner mindset.
– Jenn D.
Sep 3 '09 at 17:42




16




16




This is an excellent question to ask, if for no other reason than to help people learn how to avoid it. :)
– SunSparc
Jul 2 '13 at 21:32




This is an excellent question to ask, if for no other reason than to help people learn how to avoid it. :)
– SunSparc
Jul 2 '13 at 21:32




2




2




A further pitfall that hasn't been mentioned so far is if such a dynamically-created variable has the same name as a variable used in your logic. You essentially open up your software as a hostage to the input it is given.
– holdenweb
Dec 19 '14 at 10:50




A further pitfall that hasn't been mentioned so far is if such a dynamically-created variable has the same name as a variable used in your logic. You essentially open up your software as a hostage to the input it is given.
– holdenweb
Dec 19 '14 at 10:50




1




1




It's useful in rare places. I need it somewhere in my code, and it wouldn't cause maintenance problems.
– sudo
Jun 6 '16 at 18:50




It's useful in rare places. I need it somewhere in my code, and it wouldn't cause maintenance problems.
– sudo
Jun 6 '16 at 18:50












15 Answers
15






active

oldest

votes

















up vote
205
down vote



accepted










You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.



>>> dct = 'x': 1, 'y': 2, 'z': 3
>>> dct
'y': 2, 'x': 1, 'z': 3
>>> dct["y"]
2


You can use variable key names to achieve the effect of variable variables without the security risk.



>>> x = "spam"
>>> z = x: "eggs"
>>> z["spam"]
'eggs'


For cases where you're thinking of doing something like



var1 = 'foo'
var2 = 'bar'
var3 = 'baz'
...


a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:



l = ['foo', 'bar', 'baz']
print(l[1]) # prints bar, because indices start at 0
l.append('potatoes') # l is now ['foo', 'bar', 'baz', 'potatoes']


For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing, append, and other operations that would require awkward key management with a dict.






share|improve this answer






















  • docs.python.org/library/stdtypes.html#dict
    – Corey D
    Sep 3 '09 at 12:44










  • Edited my answer to explain dictionaries.
    – chuckharmston
    Sep 3 '09 at 12:49










  • Yeah, I understand now. Thanks.
    – Pyornide
    Sep 3 '09 at 12:54

















up vote
65
down vote













Use the built-in getattr function to get an attribute on an object by name. Modify the name as needed.



obj.spam = 'eggs'
name = 'spam'
getattr(obj, name) # returns 'eggs'





share|improve this answer






















  • That works great with a namedtuple
    – kap
    Jun 26 '15 at 8:29










  • Lovely. This is exactly what I needed. I have an object and needed to access variables by a string and I didn't want to use eval. Thanks!
    – rayryeng
    Nov 18 '16 at 23:01

















up vote
54
down vote













It's not a good idea. If you are accessing a global variable you can use globals().



>>> a = 10
>>> globals()['a']
10


If you want to access a variable in the local scope you can use locals(), but you cannot assign values to the returned dict.



A better solution is to use getattr or store your variables in a dictionary and then access them by name.






share|improve this answer


















  • 7




    Don't forget to mention that you can't modify variables through locals() (docs.python.org/library/functions.html#locals).
    – Glenn Maynard
    Sep 3 '09 at 18:43










  • You can't set variables this way. You can't do globals()['a'] = 10.
    – sudo
    Jun 6 '16 at 18:51







  • 1




    Thx, also working with locals()['x'] = "xxx"
    – oxidworks
    Jan 2 '17 at 16:10







  • 2




    @oxidworks No, it's not working. However, it may seem to work if you're in the global context, where locals() simply returns the globals() dict.
    – PM 2Ring
    Nov 17 '17 at 12:20










  • Why not use vars() built-in dictionary?
    – berkelem
    Aug 30 at 2:29

















up vote
29
down vote













Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing



$foo = "bar"
$$foo = "baz"


you write



mydict = 
foo = "bar"
mydict[foo] = "baz"


This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".






share|improve this answer



























    up vote
    16
    down vote













    New coders sometimes write code like this:



    my_calculator.button_0 = tkinter.Button(root, text=0)
    my_calculator.button_1 = tkinter.Button(root, text=1)
    my_calculator.button_2 = tkinter.Button(root, text=2)
    ...


    The coder is then left with a pile of named variables, with a coding effort of O(m * n), where m is the number of named variables and n is the number of times that group of variables needs to be accessed (including creation). The more astute beginner observes that the only difference in each of those lines is a number that changes based on a rule, and decides to use a loop. However, they get stuck on how to dynamically create those variable names, and may try something like this:



    for i in range(10):
    my_calculator.('button_%d' % i) = tkinter.Button(root, text=i)


    They soon find that this does not work.



    If the program requires arbitrary variable "names," a dictionary is the best choice, as explained in other answers. However, if you're simply trying to create many variables and you don't mind referring to them with a sequence of integers, you're probably looking for a list. This is particularly true if your data are homogeneous, such as daily temperature readings, weekly quiz scores, or a grid of graphical widgets.



    This can be assembled as follows:



    my_calculator.buttons = 
    for i in range(10):
    my_calculator.buttons.append(tkinter.Button(root, text=i))


    This list can also be created in one line with a comprehension:



    my_calculator.buttons = [tkinter.Button(root, text=i) for i in range(10)]


    The result in either case is a populated list, with the first element accessed with my_calculator.buttons[0], the next with my_calculator.buttons[1], and so on. The "base" variable name becomes the name of the list and the varying identifier is used to access it.



    Finally, don't forget other data structures, such as the set - this is similar to a dictionary, except that each "name" doesn't have a value attached to it. If you simply need a "bag" of objects, this can be a great choice. Instead of something like this:



    keyword_1 = 'apple'
    keyword_2 = 'banana'

    if query == keyword_1 or query == keyword_2:
    print('Match.')


    You will have this:



    keywords = 'apple', 'banana'
    if query in keywords:
    print('Match.')


    Use a list for a sequence of similar objects, a set for an arbitrarily-ordered bag of objects, or a dict for a bag of names with associated values.






    share|improve this answer



























      up vote
      9
      down vote













      Instead of a dictionary you can also use namedtuple from the collections module, which makes access easier.



      for example:



      #using dictionary
      variables =
      variables["first"] = 34
      variables["second"] = 45
      print variables["first"], variables["second"]

      #using namedtuple
      Variables = namedtuple('Variables', ['first', 'second'])
      vars = Variables(34, 45)
      print vars.first, vars.second





      share|improve this answer



























        up vote
        8
        down vote













        If you don't want to use any object, you can still use setattr() inside your current module:



        import sys
        current_module = module = sys.modules[__name__] # i.e the "file" where your code is written
        setattr(current_module, 'variable_name', 15) # 15 is the value you assign to the var
        print(variable_name) # >>> 15, created from a string





        share|improve this answer




















        • This one sounds better to me than using 'exec'.
          – fralau
          Dec 30 '17 at 21:13










        • This does not work with __dict__ variable however. I wonder if there is a general mechanism to create any global variable dynamically.
          – Alexey
          Jan 30 at 18:25










        • globals() can do this
          – Guillaume Lebreton
          Jan 31 at 7:42

















        up vote
        7
        down vote













        You have to use globals() built in method to achieve that behaviour:



        def var_of_var(k, v):
        globals()[k] = v

        print variable_name # NameError: name 'variable_name' is not defined
        some_name = 'variable_name'
        globals()[some_name] = 123
        print variable_name # 123

        some_name = 'variable_name2'
        var_of_var(some_name, 456)
        print variable_name2 # 456





        share|improve this answer





























          up vote
          5
          down vote













          The SimpleNamespace class could be used to create new attributes with setattr, or subclass SimpleNamespace and create your own function to add new attribute names (variables).



          from types import SimpleNamespace

          variables = "b":"B","c":"C"
          a = SimpleNamespace(**v)
          setattr(a,"g","G")
          a.g = "G+"
          something = a.a





          share|improve this answer





























            up vote
            3
            down vote













            I'm am answering the question: How to get the value of a variable given its name in a string?
            which is closed as a duplicate with a link to this question.



            If the variables in question are part of an object (part of a class for example) then some useful functions to achieve exactly that are hasattr, getattr, and setattr.



            So for example you can have:



            class Variables(object):
            def __init__(self):
            self.foo = "initial_variable"
            def create_new_var(self,name,value):
            setattr(self,name,value)
            def get_var(self,name):
            if hasattr(self,name):
            return getattr(self,name)
            else:
            raise("Class does not have a variable named: "+name)


            Then you can do:



            v = Variables()
            v.get_var("foo")



            "initial_variable"




            v.create_new_var(v.foo,"is actually not initial")
            v.initial_variable



            "is actually not initial"







            share|improve this answer





























              up vote
              1
              down vote













              The consensus is to use a dictionary for this - see the other answers. This is a good idea for most cases, however, there are many aspects arising from this:



              • you'll yourself be responsible for this dictionary, including garbage collection (of in-dict variables) etc.

              • there's either no locality or globality for variable variables, it depends on the globality of the dictionary

              • if you want to rename a variable name, you'll have to do it manually

              • however, you are much more flexible, e.g.

                • you can decide to overwrite existing variables or ...

                • ... choose to implement const variables

                • to raise an exception on overwriting for different types

                • etc.


              That said, I've implemented a variable variables manager-class which provides some of the above ideas. It works for python 2 and 3.



              You'd use the class like this:



              from variableVariablesManager import VariableVariablesManager

              myVars = VariableVariablesManager()
              myVars['test'] = 25
              print(myVars['test'])

              # define a const variable
              myVars.defineConstVariable('myconst', 13)
              try:
              myVars['myconst'] = 14 # <- this raises an error, since 'myconst' must not be changed
              print("not allowed")
              except AttributeError as e:
              pass

              # rename a variable
              myVars.renameVariable('myconst', 'myconstOther')

              # preserve locality
              def testLocalVar():
              myVars = VariableVariablesManager()
              myVars['test'] = 13
              print("inside function myVars['test']:", myVars['test'])
              testLocalVar()
              print("outside function myVars['test']:", myVars['test'])

              # define a global variable
              myVars.defineGlobalVariable('globalVar', 12)
              def testGlobalVar():
              myVars = VariableVariablesManager()
              print("inside function myVars['globalVar']:", myVars['globalVar'])
              myVars['globalVar'] = 13
              print("inside function myVars['globalVar'] (having been changed):", myVars['globalVar'])
              testGlobalVar()
              print("outside function myVars['globalVar']:", myVars['globalVar'])


              If you wish to allow overwriting of variables with the same type only:



              myVars = VariableVariablesManager(enforceSameTypeOnOverride = True)
              myVars['test'] = 25
              myVars['test'] = "Cat" # <- raises Exception (different type on overwriting)





              share|improve this answer






















              • At first glance the long camelised imports made me think this was Java.
                – markroxor
                Feb 19 at 6:17

















              up vote
              1
              down vote













              Please refer following example to create variables runtime. You can use globals().



              for i in range(3):
              globals() ['variable_'+str(i)] = i


              In the above example, I want to create three variables: variable_0, variable_1 and variable_2 at runtime with values 0,1 and 2 respectively.



              variable_0
              [Output]:0

              variable_1
              [Output]:1

              variable_2
              [Output]:2


              To access the value of variables created at runtime, you can use eval() method as follows:



              for i in range(3):
              globals() ['variable_'+str(i)] = i
              print('Variable Value:',eval('variable_'+str(i)))

              [Output]:
              Variable Value: 0
              Variable Value: 1
              Variable Value: 2





              share|improve this answer



























                up vote
                0
                down vote













                Any set of variables can also be wrapped up in a class.
                "Variable" variables may be added to the class instance during runtime by directly accessing the built-in dictionary through __dict__ attribute.



                The following code defines Variables class, which adds variables (in this case attributes) to its instance during the construction. Variable names are taken from a specified list (which, for example, could have been generated by program code):



                # some list of variable names
                L = ['a', 'b', 'c']

                class Variables:
                def __init__(self, L):
                for item in L:
                self.__dict__[item] = 100

                v = Variables(L)
                print(v.a, v.b, v.c)
                #will produce 100 100 100





                share|improve this answer



























                  up vote
                  0
                  down vote













                  Use globals()



                  You can actually assign variables to global scope dynamically, for instance, if you want 10 variables that can be accessed on a global scope i_1, i_2 ... i_10:



                  for i in range(10):
                  globals()['i_'.format(i)] = 'a'


                  This will assign 'a' to all of these 10 variables, of course you can change the value dynamically as well. All of these variables can be accessed now like other globally declared variable:



                  >>> i_5
                  'a'





                  share|improve this answer



























                    up vote
                    -1
                    down vote













                    a = 'hi'
                    # the expression below is a dynamic way of saying: b = 'by'
                    locals()['b'] = 'by'

                    print(a)
                    # 'hi'
                    print(b)
                    # 'by'





                    share|improve this answer


















                    • 1




                      Try to add details while answering.
                      – M.A.K. Ripon
                      Oct 7 at 17:12









                    protected by Bhargav Rao Apr 21 '16 at 15:03



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?













                    15 Answers
                    15






                    active

                    oldest

                    votes








                    15 Answers
                    15






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes








                    up vote
                    205
                    down vote



                    accepted










                    You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.



                    >>> dct = 'x': 1, 'y': 2, 'z': 3
                    >>> dct
                    'y': 2, 'x': 1, 'z': 3
                    >>> dct["y"]
                    2


                    You can use variable key names to achieve the effect of variable variables without the security risk.



                    >>> x = "spam"
                    >>> z = x: "eggs"
                    >>> z["spam"]
                    'eggs'


                    For cases where you're thinking of doing something like



                    var1 = 'foo'
                    var2 = 'bar'
                    var3 = 'baz'
                    ...


                    a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:



                    l = ['foo', 'bar', 'baz']
                    print(l[1]) # prints bar, because indices start at 0
                    l.append('potatoes') # l is now ['foo', 'bar', 'baz', 'potatoes']


                    For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing, append, and other operations that would require awkward key management with a dict.






                    share|improve this answer






















                    • docs.python.org/library/stdtypes.html#dict
                      – Corey D
                      Sep 3 '09 at 12:44










                    • Edited my answer to explain dictionaries.
                      – chuckharmston
                      Sep 3 '09 at 12:49










                    • Yeah, I understand now. Thanks.
                      – Pyornide
                      Sep 3 '09 at 12:54














                    up vote
                    205
                    down vote



                    accepted










                    You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.



                    >>> dct = 'x': 1, 'y': 2, 'z': 3
                    >>> dct
                    'y': 2, 'x': 1, 'z': 3
                    >>> dct["y"]
                    2


                    You can use variable key names to achieve the effect of variable variables without the security risk.



                    >>> x = "spam"
                    >>> z = x: "eggs"
                    >>> z["spam"]
                    'eggs'


                    For cases where you're thinking of doing something like



                    var1 = 'foo'
                    var2 = 'bar'
                    var3 = 'baz'
                    ...


                    a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:



                    l = ['foo', 'bar', 'baz']
                    print(l[1]) # prints bar, because indices start at 0
                    l.append('potatoes') # l is now ['foo', 'bar', 'baz', 'potatoes']


                    For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing, append, and other operations that would require awkward key management with a dict.






                    share|improve this answer






















                    • docs.python.org/library/stdtypes.html#dict
                      – Corey D
                      Sep 3 '09 at 12:44










                    • Edited my answer to explain dictionaries.
                      – chuckharmston
                      Sep 3 '09 at 12:49










                    • Yeah, I understand now. Thanks.
                      – Pyornide
                      Sep 3 '09 at 12:54












                    up vote
                    205
                    down vote



                    accepted







                    up vote
                    205
                    down vote



                    accepted






                    You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.



                    >>> dct = 'x': 1, 'y': 2, 'z': 3
                    >>> dct
                    'y': 2, 'x': 1, 'z': 3
                    >>> dct["y"]
                    2


                    You can use variable key names to achieve the effect of variable variables without the security risk.



                    >>> x = "spam"
                    >>> z = x: "eggs"
                    >>> z["spam"]
                    'eggs'


                    For cases where you're thinking of doing something like



                    var1 = 'foo'
                    var2 = 'bar'
                    var3 = 'baz'
                    ...


                    a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:



                    l = ['foo', 'bar', 'baz']
                    print(l[1]) # prints bar, because indices start at 0
                    l.append('potatoes') # l is now ['foo', 'bar', 'baz', 'potatoes']


                    For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing, append, and other operations that would require awkward key management with a dict.






                    share|improve this answer














                    You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.



                    >>> dct = 'x': 1, 'y': 2, 'z': 3
                    >>> dct
                    'y': 2, 'x': 1, 'z': 3
                    >>> dct["y"]
                    2


                    You can use variable key names to achieve the effect of variable variables without the security risk.



                    >>> x = "spam"
                    >>> z = x: "eggs"
                    >>> z["spam"]
                    'eggs'


                    For cases where you're thinking of doing something like



                    var1 = 'foo'
                    var2 = 'bar'
                    var3 = 'baz'
                    ...


                    a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:



                    l = ['foo', 'bar', 'baz']
                    print(l[1]) # prints bar, because indices start at 0
                    l.append('potatoes') # l is now ['foo', 'bar', 'baz', 'potatoes']


                    For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing, append, and other operations that would require awkward key management with a dict.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 27 '17 at 2:37









                    user2357112

                    148k12153242




                    148k12153242










                    answered Sep 3 '09 at 12:41







                    c_harm


















                    • docs.python.org/library/stdtypes.html#dict
                      – Corey D
                      Sep 3 '09 at 12:44










                    • Edited my answer to explain dictionaries.
                      – chuckharmston
                      Sep 3 '09 at 12:49










                    • Yeah, I understand now. Thanks.
                      – Pyornide
                      Sep 3 '09 at 12:54
















                    • docs.python.org/library/stdtypes.html#dict
                      – Corey D
                      Sep 3 '09 at 12:44










                    • Edited my answer to explain dictionaries.
                      – chuckharmston
                      Sep 3 '09 at 12:49










                    • Yeah, I understand now. Thanks.
                      – Pyornide
                      Sep 3 '09 at 12:54















                    docs.python.org/library/stdtypes.html#dict
                    – Corey D
                    Sep 3 '09 at 12:44




                    docs.python.org/library/stdtypes.html#dict
                    – Corey D
                    Sep 3 '09 at 12:44












                    Edited my answer to explain dictionaries.
                    – chuckharmston
                    Sep 3 '09 at 12:49




                    Edited my answer to explain dictionaries.
                    – chuckharmston
                    Sep 3 '09 at 12:49












                    Yeah, I understand now. Thanks.
                    – Pyornide
                    Sep 3 '09 at 12:54




                    Yeah, I understand now. Thanks.
                    – Pyornide
                    Sep 3 '09 at 12:54












                    up vote
                    65
                    down vote













                    Use the built-in getattr function to get an attribute on an object by name. Modify the name as needed.



                    obj.spam = 'eggs'
                    name = 'spam'
                    getattr(obj, name) # returns 'eggs'





                    share|improve this answer






















                    • That works great with a namedtuple
                      – kap
                      Jun 26 '15 at 8:29










                    • Lovely. This is exactly what I needed. I have an object and needed to access variables by a string and I didn't want to use eval. Thanks!
                      – rayryeng
                      Nov 18 '16 at 23:01














                    up vote
                    65
                    down vote













                    Use the built-in getattr function to get an attribute on an object by name. Modify the name as needed.



                    obj.spam = 'eggs'
                    name = 'spam'
                    getattr(obj, name) # returns 'eggs'





                    share|improve this answer






















                    • That works great with a namedtuple
                      – kap
                      Jun 26 '15 at 8:29










                    • Lovely. This is exactly what I needed. I have an object and needed to access variables by a string and I didn't want to use eval. Thanks!
                      – rayryeng
                      Nov 18 '16 at 23:01












                    up vote
                    65
                    down vote










                    up vote
                    65
                    down vote









                    Use the built-in getattr function to get an attribute on an object by name. Modify the name as needed.



                    obj.spam = 'eggs'
                    name = 'spam'
                    getattr(obj, name) # returns 'eggs'





                    share|improve this answer














                    Use the built-in getattr function to get an attribute on an object by name. Modify the name as needed.



                    obj.spam = 'eggs'
                    name = 'spam'
                    getattr(obj, name) # returns 'eggs'






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 21 '16 at 15:23









                    davidism

                    61.3k12154173




                    61.3k12154173










                    answered Sep 3 '09 at 12:43









                    SilentGhost

                    189k46262262




                    189k46262262











                    • That works great with a namedtuple
                      – kap
                      Jun 26 '15 at 8:29










                    • Lovely. This is exactly what I needed. I have an object and needed to access variables by a string and I didn't want to use eval. Thanks!
                      – rayryeng
                      Nov 18 '16 at 23:01
















                    • That works great with a namedtuple
                      – kap
                      Jun 26 '15 at 8:29










                    • Lovely. This is exactly what I needed. I have an object and needed to access variables by a string and I didn't want to use eval. Thanks!
                      – rayryeng
                      Nov 18 '16 at 23:01















                    That works great with a namedtuple
                    – kap
                    Jun 26 '15 at 8:29




                    That works great with a namedtuple
                    – kap
                    Jun 26 '15 at 8:29












                    Lovely. This is exactly what I needed. I have an object and needed to access variables by a string and I didn't want to use eval. Thanks!
                    – rayryeng
                    Nov 18 '16 at 23:01




                    Lovely. This is exactly what I needed. I have an object and needed to access variables by a string and I didn't want to use eval. Thanks!
                    – rayryeng
                    Nov 18 '16 at 23:01










                    up vote
                    54
                    down vote













                    It's not a good idea. If you are accessing a global variable you can use globals().



                    >>> a = 10
                    >>> globals()['a']
                    10


                    If you want to access a variable in the local scope you can use locals(), but you cannot assign values to the returned dict.



                    A better solution is to use getattr or store your variables in a dictionary and then access them by name.






                    share|improve this answer


















                    • 7




                      Don't forget to mention that you can't modify variables through locals() (docs.python.org/library/functions.html#locals).
                      – Glenn Maynard
                      Sep 3 '09 at 18:43










                    • You can't set variables this way. You can't do globals()['a'] = 10.
                      – sudo
                      Jun 6 '16 at 18:51







                    • 1




                      Thx, also working with locals()['x'] = "xxx"
                      – oxidworks
                      Jan 2 '17 at 16:10







                    • 2




                      @oxidworks No, it's not working. However, it may seem to work if you're in the global context, where locals() simply returns the globals() dict.
                      – PM 2Ring
                      Nov 17 '17 at 12:20










                    • Why not use vars() built-in dictionary?
                      – berkelem
                      Aug 30 at 2:29














                    up vote
                    54
                    down vote













                    It's not a good idea. If you are accessing a global variable you can use globals().



                    >>> a = 10
                    >>> globals()['a']
                    10


                    If you want to access a variable in the local scope you can use locals(), but you cannot assign values to the returned dict.



                    A better solution is to use getattr or store your variables in a dictionary and then access them by name.






                    share|improve this answer


















                    • 7




                      Don't forget to mention that you can't modify variables through locals() (docs.python.org/library/functions.html#locals).
                      – Glenn Maynard
                      Sep 3 '09 at 18:43










                    • You can't set variables this way. You can't do globals()['a'] = 10.
                      – sudo
                      Jun 6 '16 at 18:51







                    • 1




                      Thx, also working with locals()['x'] = "xxx"
                      – oxidworks
                      Jan 2 '17 at 16:10







                    • 2




                      @oxidworks No, it's not working. However, it may seem to work if you're in the global context, where locals() simply returns the globals() dict.
                      – PM 2Ring
                      Nov 17 '17 at 12:20










                    • Why not use vars() built-in dictionary?
                      – berkelem
                      Aug 30 at 2:29












                    up vote
                    54
                    down vote










                    up vote
                    54
                    down vote









                    It's not a good idea. If you are accessing a global variable you can use globals().



                    >>> a = 10
                    >>> globals()['a']
                    10


                    If you want to access a variable in the local scope you can use locals(), but you cannot assign values to the returned dict.



                    A better solution is to use getattr or store your variables in a dictionary and then access them by name.






                    share|improve this answer














                    It's not a good idea. If you are accessing a global variable you can use globals().



                    >>> a = 10
                    >>> globals()['a']
                    10


                    If you want to access a variable in the local scope you can use locals(), but you cannot assign values to the returned dict.



                    A better solution is to use getattr or store your variables in a dictionary and then access them by name.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 24 '17 at 2:03









                    Vallentin

                    11.3k42949




                    11.3k42949










                    answered Sep 3 '09 at 12:43









                    Nadia Alramli

                    77.7k24153147




                    77.7k24153147







                    • 7




                      Don't forget to mention that you can't modify variables through locals() (docs.python.org/library/functions.html#locals).
                      – Glenn Maynard
                      Sep 3 '09 at 18:43










                    • You can't set variables this way. You can't do globals()['a'] = 10.
                      – sudo
                      Jun 6 '16 at 18:51







                    • 1




                      Thx, also working with locals()['x'] = "xxx"
                      – oxidworks
                      Jan 2 '17 at 16:10







                    • 2




                      @oxidworks No, it's not working. However, it may seem to work if you're in the global context, where locals() simply returns the globals() dict.
                      – PM 2Ring
                      Nov 17 '17 at 12:20










                    • Why not use vars() built-in dictionary?
                      – berkelem
                      Aug 30 at 2:29












                    • 7




                      Don't forget to mention that you can't modify variables through locals() (docs.python.org/library/functions.html#locals).
                      – Glenn Maynard
                      Sep 3 '09 at 18:43










                    • You can't set variables this way. You can't do globals()['a'] = 10.
                      – sudo
                      Jun 6 '16 at 18:51







                    • 1




                      Thx, also working with locals()['x'] = "xxx"
                      – oxidworks
                      Jan 2 '17 at 16:10







                    • 2




                      @oxidworks No, it's not working. However, it may seem to work if you're in the global context, where locals() simply returns the globals() dict.
                      – PM 2Ring
                      Nov 17 '17 at 12:20










                    • Why not use vars() built-in dictionary?
                      – berkelem
                      Aug 30 at 2:29







                    7




                    7




                    Don't forget to mention that you can't modify variables through locals() (docs.python.org/library/functions.html#locals).
                    – Glenn Maynard
                    Sep 3 '09 at 18:43




                    Don't forget to mention that you can't modify variables through locals() (docs.python.org/library/functions.html#locals).
                    – Glenn Maynard
                    Sep 3 '09 at 18:43












                    You can't set variables this way. You can't do globals()['a'] = 10.
                    – sudo
                    Jun 6 '16 at 18:51





                    You can't set variables this way. You can't do globals()['a'] = 10.
                    – sudo
                    Jun 6 '16 at 18:51





                    1




                    1




                    Thx, also working with locals()['x'] = "xxx"
                    – oxidworks
                    Jan 2 '17 at 16:10





                    Thx, also working with locals()['x'] = "xxx"
                    – oxidworks
                    Jan 2 '17 at 16:10





                    2




                    2




                    @oxidworks No, it's not working. However, it may seem to work if you're in the global context, where locals() simply returns the globals() dict.
                    – PM 2Ring
                    Nov 17 '17 at 12:20




                    @oxidworks No, it's not working. However, it may seem to work if you're in the global context, where locals() simply returns the globals() dict.
                    – PM 2Ring
                    Nov 17 '17 at 12:20












                    Why not use vars() built-in dictionary?
                    – berkelem
                    Aug 30 at 2:29




                    Why not use vars() built-in dictionary?
                    – berkelem
                    Aug 30 at 2:29










                    up vote
                    29
                    down vote













                    Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing



                    $foo = "bar"
                    $$foo = "baz"


                    you write



                    mydict = 
                    foo = "bar"
                    mydict[foo] = "baz"


                    This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".






                    share|improve this answer
























                      up vote
                      29
                      down vote













                      Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing



                      $foo = "bar"
                      $$foo = "baz"


                      you write



                      mydict = 
                      foo = "bar"
                      mydict[foo] = "baz"


                      This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".






                      share|improve this answer






















                        up vote
                        29
                        down vote










                        up vote
                        29
                        down vote









                        Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing



                        $foo = "bar"
                        $$foo = "baz"


                        you write



                        mydict = 
                        foo = "bar"
                        mydict[foo] = "baz"


                        This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".






                        share|improve this answer












                        Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing



                        $foo = "bar"
                        $$foo = "baz"


                        you write



                        mydict = 
                        foo = "bar"
                        mydict[foo] = "baz"


                        This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Sep 3 '09 at 12:42









                        sepp2k

                        291k37592604




                        291k37592604




















                            up vote
                            16
                            down vote













                            New coders sometimes write code like this:



                            my_calculator.button_0 = tkinter.Button(root, text=0)
                            my_calculator.button_1 = tkinter.Button(root, text=1)
                            my_calculator.button_2 = tkinter.Button(root, text=2)
                            ...


                            The coder is then left with a pile of named variables, with a coding effort of O(m * n), where m is the number of named variables and n is the number of times that group of variables needs to be accessed (including creation). The more astute beginner observes that the only difference in each of those lines is a number that changes based on a rule, and decides to use a loop. However, they get stuck on how to dynamically create those variable names, and may try something like this:



                            for i in range(10):
                            my_calculator.('button_%d' % i) = tkinter.Button(root, text=i)


                            They soon find that this does not work.



                            If the program requires arbitrary variable "names," a dictionary is the best choice, as explained in other answers. However, if you're simply trying to create many variables and you don't mind referring to them with a sequence of integers, you're probably looking for a list. This is particularly true if your data are homogeneous, such as daily temperature readings, weekly quiz scores, or a grid of graphical widgets.



                            This can be assembled as follows:



                            my_calculator.buttons = 
                            for i in range(10):
                            my_calculator.buttons.append(tkinter.Button(root, text=i))


                            This list can also be created in one line with a comprehension:



                            my_calculator.buttons = [tkinter.Button(root, text=i) for i in range(10)]


                            The result in either case is a populated list, with the first element accessed with my_calculator.buttons[0], the next with my_calculator.buttons[1], and so on. The "base" variable name becomes the name of the list and the varying identifier is used to access it.



                            Finally, don't forget other data structures, such as the set - this is similar to a dictionary, except that each "name" doesn't have a value attached to it. If you simply need a "bag" of objects, this can be a great choice. Instead of something like this:



                            keyword_1 = 'apple'
                            keyword_2 = 'banana'

                            if query == keyword_1 or query == keyword_2:
                            print('Match.')


                            You will have this:



                            keywords = 'apple', 'banana'
                            if query in keywords:
                            print('Match.')


                            Use a list for a sequence of similar objects, a set for an arbitrarily-ordered bag of objects, or a dict for a bag of names with associated values.






                            share|improve this answer
























                              up vote
                              16
                              down vote













                              New coders sometimes write code like this:



                              my_calculator.button_0 = tkinter.Button(root, text=0)
                              my_calculator.button_1 = tkinter.Button(root, text=1)
                              my_calculator.button_2 = tkinter.Button(root, text=2)
                              ...


                              The coder is then left with a pile of named variables, with a coding effort of O(m * n), where m is the number of named variables and n is the number of times that group of variables needs to be accessed (including creation). The more astute beginner observes that the only difference in each of those lines is a number that changes based on a rule, and decides to use a loop. However, they get stuck on how to dynamically create those variable names, and may try something like this:



                              for i in range(10):
                              my_calculator.('button_%d' % i) = tkinter.Button(root, text=i)


                              They soon find that this does not work.



                              If the program requires arbitrary variable "names," a dictionary is the best choice, as explained in other answers. However, if you're simply trying to create many variables and you don't mind referring to them with a sequence of integers, you're probably looking for a list. This is particularly true if your data are homogeneous, such as daily temperature readings, weekly quiz scores, or a grid of graphical widgets.



                              This can be assembled as follows:



                              my_calculator.buttons = 
                              for i in range(10):
                              my_calculator.buttons.append(tkinter.Button(root, text=i))


                              This list can also be created in one line with a comprehension:



                              my_calculator.buttons = [tkinter.Button(root, text=i) for i in range(10)]


                              The result in either case is a populated list, with the first element accessed with my_calculator.buttons[0], the next with my_calculator.buttons[1], and so on. The "base" variable name becomes the name of the list and the varying identifier is used to access it.



                              Finally, don't forget other data structures, such as the set - this is similar to a dictionary, except that each "name" doesn't have a value attached to it. If you simply need a "bag" of objects, this can be a great choice. Instead of something like this:



                              keyword_1 = 'apple'
                              keyword_2 = 'banana'

                              if query == keyword_1 or query == keyword_2:
                              print('Match.')


                              You will have this:



                              keywords = 'apple', 'banana'
                              if query in keywords:
                              print('Match.')


                              Use a list for a sequence of similar objects, a set for an arbitrarily-ordered bag of objects, or a dict for a bag of names with associated values.






                              share|improve this answer






















                                up vote
                                16
                                down vote










                                up vote
                                16
                                down vote









                                New coders sometimes write code like this:



                                my_calculator.button_0 = tkinter.Button(root, text=0)
                                my_calculator.button_1 = tkinter.Button(root, text=1)
                                my_calculator.button_2 = tkinter.Button(root, text=2)
                                ...


                                The coder is then left with a pile of named variables, with a coding effort of O(m * n), where m is the number of named variables and n is the number of times that group of variables needs to be accessed (including creation). The more astute beginner observes that the only difference in each of those lines is a number that changes based on a rule, and decides to use a loop. However, they get stuck on how to dynamically create those variable names, and may try something like this:



                                for i in range(10):
                                my_calculator.('button_%d' % i) = tkinter.Button(root, text=i)


                                They soon find that this does not work.



                                If the program requires arbitrary variable "names," a dictionary is the best choice, as explained in other answers. However, if you're simply trying to create many variables and you don't mind referring to them with a sequence of integers, you're probably looking for a list. This is particularly true if your data are homogeneous, such as daily temperature readings, weekly quiz scores, or a grid of graphical widgets.



                                This can be assembled as follows:



                                my_calculator.buttons = 
                                for i in range(10):
                                my_calculator.buttons.append(tkinter.Button(root, text=i))


                                This list can also be created in one line with a comprehension:



                                my_calculator.buttons = [tkinter.Button(root, text=i) for i in range(10)]


                                The result in either case is a populated list, with the first element accessed with my_calculator.buttons[0], the next with my_calculator.buttons[1], and so on. The "base" variable name becomes the name of the list and the varying identifier is used to access it.



                                Finally, don't forget other data structures, such as the set - this is similar to a dictionary, except that each "name" doesn't have a value attached to it. If you simply need a "bag" of objects, this can be a great choice. Instead of something like this:



                                keyword_1 = 'apple'
                                keyword_2 = 'banana'

                                if query == keyword_1 or query == keyword_2:
                                print('Match.')


                                You will have this:



                                keywords = 'apple', 'banana'
                                if query in keywords:
                                print('Match.')


                                Use a list for a sequence of similar objects, a set for an arbitrarily-ordered bag of objects, or a dict for a bag of names with associated values.






                                share|improve this answer












                                New coders sometimes write code like this:



                                my_calculator.button_0 = tkinter.Button(root, text=0)
                                my_calculator.button_1 = tkinter.Button(root, text=1)
                                my_calculator.button_2 = tkinter.Button(root, text=2)
                                ...


                                The coder is then left with a pile of named variables, with a coding effort of O(m * n), where m is the number of named variables and n is the number of times that group of variables needs to be accessed (including creation). The more astute beginner observes that the only difference in each of those lines is a number that changes based on a rule, and decides to use a loop. However, they get stuck on how to dynamically create those variable names, and may try something like this:



                                for i in range(10):
                                my_calculator.('button_%d' % i) = tkinter.Button(root, text=i)


                                They soon find that this does not work.



                                If the program requires arbitrary variable "names," a dictionary is the best choice, as explained in other answers. However, if you're simply trying to create many variables and you don't mind referring to them with a sequence of integers, you're probably looking for a list. This is particularly true if your data are homogeneous, such as daily temperature readings, weekly quiz scores, or a grid of graphical widgets.



                                This can be assembled as follows:



                                my_calculator.buttons = 
                                for i in range(10):
                                my_calculator.buttons.append(tkinter.Button(root, text=i))


                                This list can also be created in one line with a comprehension:



                                my_calculator.buttons = [tkinter.Button(root, text=i) for i in range(10)]


                                The result in either case is a populated list, with the first element accessed with my_calculator.buttons[0], the next with my_calculator.buttons[1], and so on. The "base" variable name becomes the name of the list and the varying identifier is used to access it.



                                Finally, don't forget other data structures, such as the set - this is similar to a dictionary, except that each "name" doesn't have a value attached to it. If you simply need a "bag" of objects, this can be a great choice. Instead of something like this:



                                keyword_1 = 'apple'
                                keyword_2 = 'banana'

                                if query == keyword_1 or query == keyword_2:
                                print('Match.')


                                You will have this:



                                keywords = 'apple', 'banana'
                                if query in keywords:
                                print('Match.')


                                Use a list for a sequence of similar objects, a set for an arbitrarily-ordered bag of objects, or a dict for a bag of names with associated values.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Aug 16 '16 at 10:41









                                TigerhawkT3

                                39k53465




                                39k53465




















                                    up vote
                                    9
                                    down vote













                                    Instead of a dictionary you can also use namedtuple from the collections module, which makes access easier.



                                    for example:



                                    #using dictionary
                                    variables =
                                    variables["first"] = 34
                                    variables["second"] = 45
                                    print variables["first"], variables["second"]

                                    #using namedtuple
                                    Variables = namedtuple('Variables', ['first', 'second'])
                                    vars = Variables(34, 45)
                                    print vars.first, vars.second





                                    share|improve this answer
























                                      up vote
                                      9
                                      down vote













                                      Instead of a dictionary you can also use namedtuple from the collections module, which makes access easier.



                                      for example:



                                      #using dictionary
                                      variables =
                                      variables["first"] = 34
                                      variables["second"] = 45
                                      print variables["first"], variables["second"]

                                      #using namedtuple
                                      Variables = namedtuple('Variables', ['first', 'second'])
                                      vars = Variables(34, 45)
                                      print vars.first, vars.second





                                      share|improve this answer






















                                        up vote
                                        9
                                        down vote










                                        up vote
                                        9
                                        down vote









                                        Instead of a dictionary you can also use namedtuple from the collections module, which makes access easier.



                                        for example:



                                        #using dictionary
                                        variables =
                                        variables["first"] = 34
                                        variables["second"] = 45
                                        print variables["first"], variables["second"]

                                        #using namedtuple
                                        Variables = namedtuple('Variables', ['first', 'second'])
                                        vars = Variables(34, 45)
                                        print vars.first, vars.second





                                        share|improve this answer












                                        Instead of a dictionary you can also use namedtuple from the collections module, which makes access easier.



                                        for example:



                                        #using dictionary
                                        variables =
                                        variables["first"] = 34
                                        variables["second"] = 45
                                        print variables["first"], variables["second"]

                                        #using namedtuple
                                        Variables = namedtuple('Variables', ['first', 'second'])
                                        vars = Variables(34, 45)
                                        print vars.first, vars.second






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jun 22 '16 at 15:09









                                        ojas mohril

                                        96489




                                        96489




















                                            up vote
                                            8
                                            down vote













                                            If you don't want to use any object, you can still use setattr() inside your current module:



                                            import sys
                                            current_module = module = sys.modules[__name__] # i.e the "file" where your code is written
                                            setattr(current_module, 'variable_name', 15) # 15 is the value you assign to the var
                                            print(variable_name) # >>> 15, created from a string





                                            share|improve this answer




















                                            • This one sounds better to me than using 'exec'.
                                              – fralau
                                              Dec 30 '17 at 21:13










                                            • This does not work with __dict__ variable however. I wonder if there is a general mechanism to create any global variable dynamically.
                                              – Alexey
                                              Jan 30 at 18:25










                                            • globals() can do this
                                              – Guillaume Lebreton
                                              Jan 31 at 7:42














                                            up vote
                                            8
                                            down vote













                                            If you don't want to use any object, you can still use setattr() inside your current module:



                                            import sys
                                            current_module = module = sys.modules[__name__] # i.e the "file" where your code is written
                                            setattr(current_module, 'variable_name', 15) # 15 is the value you assign to the var
                                            print(variable_name) # >>> 15, created from a string





                                            share|improve this answer




















                                            • This one sounds better to me than using 'exec'.
                                              – fralau
                                              Dec 30 '17 at 21:13










                                            • This does not work with __dict__ variable however. I wonder if there is a general mechanism to create any global variable dynamically.
                                              – Alexey
                                              Jan 30 at 18:25










                                            • globals() can do this
                                              – Guillaume Lebreton
                                              Jan 31 at 7:42












                                            up vote
                                            8
                                            down vote










                                            up vote
                                            8
                                            down vote









                                            If you don't want to use any object, you can still use setattr() inside your current module:



                                            import sys
                                            current_module = module = sys.modules[__name__] # i.e the "file" where your code is written
                                            setattr(current_module, 'variable_name', 15) # 15 is the value you assign to the var
                                            print(variable_name) # >>> 15, created from a string





                                            share|improve this answer












                                            If you don't want to use any object, you can still use setattr() inside your current module:



                                            import sys
                                            current_module = module = sys.modules[__name__] # i.e the "file" where your code is written
                                            setattr(current_module, 'variable_name', 15) # 15 is the value you assign to the var
                                            print(variable_name) # >>> 15, created from a string






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Oct 23 '17 at 19:24









                                            Guillaume Lebreton

                                            465511




                                            465511











                                            • This one sounds better to me than using 'exec'.
                                              – fralau
                                              Dec 30 '17 at 21:13










                                            • This does not work with __dict__ variable however. I wonder if there is a general mechanism to create any global variable dynamically.
                                              – Alexey
                                              Jan 30 at 18:25










                                            • globals() can do this
                                              – Guillaume Lebreton
                                              Jan 31 at 7:42
















                                            • This one sounds better to me than using 'exec'.
                                              – fralau
                                              Dec 30 '17 at 21:13










                                            • This does not work with __dict__ variable however. I wonder if there is a general mechanism to create any global variable dynamically.
                                              – Alexey
                                              Jan 30 at 18:25










                                            • globals() can do this
                                              – Guillaume Lebreton
                                              Jan 31 at 7:42















                                            This one sounds better to me than using 'exec'.
                                            – fralau
                                            Dec 30 '17 at 21:13




                                            This one sounds better to me than using 'exec'.
                                            – fralau
                                            Dec 30 '17 at 21:13












                                            This does not work with __dict__ variable however. I wonder if there is a general mechanism to create any global variable dynamically.
                                            – Alexey
                                            Jan 30 at 18:25




                                            This does not work with __dict__ variable however. I wonder if there is a general mechanism to create any global variable dynamically.
                                            – Alexey
                                            Jan 30 at 18:25












                                            globals() can do this
                                            – Guillaume Lebreton
                                            Jan 31 at 7:42




                                            globals() can do this
                                            – Guillaume Lebreton
                                            Jan 31 at 7:42










                                            up vote
                                            7
                                            down vote













                                            You have to use globals() built in method to achieve that behaviour:



                                            def var_of_var(k, v):
                                            globals()[k] = v

                                            print variable_name # NameError: name 'variable_name' is not defined
                                            some_name = 'variable_name'
                                            globals()[some_name] = 123
                                            print variable_name # 123

                                            some_name = 'variable_name2'
                                            var_of_var(some_name, 456)
                                            print variable_name2 # 456





                                            share|improve this answer


























                                              up vote
                                              7
                                              down vote













                                              You have to use globals() built in method to achieve that behaviour:



                                              def var_of_var(k, v):
                                              globals()[k] = v

                                              print variable_name # NameError: name 'variable_name' is not defined
                                              some_name = 'variable_name'
                                              globals()[some_name] = 123
                                              print variable_name # 123

                                              some_name = 'variable_name2'
                                              var_of_var(some_name, 456)
                                              print variable_name2 # 456





                                              share|improve this answer
























                                                up vote
                                                7
                                                down vote










                                                up vote
                                                7
                                                down vote









                                                You have to use globals() built in method to achieve that behaviour:



                                                def var_of_var(k, v):
                                                globals()[k] = v

                                                print variable_name # NameError: name 'variable_name' is not defined
                                                some_name = 'variable_name'
                                                globals()[some_name] = 123
                                                print variable_name # 123

                                                some_name = 'variable_name2'
                                                var_of_var(some_name, 456)
                                                print variable_name2 # 456





                                                share|improve this answer














                                                You have to use globals() built in method to achieve that behaviour:



                                                def var_of_var(k, v):
                                                globals()[k] = v

                                                print variable_name # NameError: name 'variable_name' is not defined
                                                some_name = 'variable_name'
                                                globals()[some_name] = 123
                                                print variable_name # 123

                                                some_name = 'variable_name2'
                                                var_of_var(some_name, 456)
                                                print variable_name2 # 456






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Apr 24 '17 at 2:04









                                                Vallentin

                                                11.3k42949




                                                11.3k42949










                                                answered Jun 9 '16 at 12:14









                                                Andriy Ivaneyko

                                                10.5k32340




                                                10.5k32340




















                                                    up vote
                                                    5
                                                    down vote













                                                    The SimpleNamespace class could be used to create new attributes with setattr, or subclass SimpleNamespace and create your own function to add new attribute names (variables).



                                                    from types import SimpleNamespace

                                                    variables = "b":"B","c":"C"
                                                    a = SimpleNamespace(**v)
                                                    setattr(a,"g","G")
                                                    a.g = "G+"
                                                    something = a.a





                                                    share|improve this answer


























                                                      up vote
                                                      5
                                                      down vote













                                                      The SimpleNamespace class could be used to create new attributes with setattr, or subclass SimpleNamespace and create your own function to add new attribute names (variables).



                                                      from types import SimpleNamespace

                                                      variables = "b":"B","c":"C"
                                                      a = SimpleNamespace(**v)
                                                      setattr(a,"g","G")
                                                      a.g = "G+"
                                                      something = a.a





                                                      share|improve this answer
























                                                        up vote
                                                        5
                                                        down vote










                                                        up vote
                                                        5
                                                        down vote









                                                        The SimpleNamespace class could be used to create new attributes with setattr, or subclass SimpleNamespace and create your own function to add new attribute names (variables).



                                                        from types import SimpleNamespace

                                                        variables = "b":"B","c":"C"
                                                        a = SimpleNamespace(**v)
                                                        setattr(a,"g","G")
                                                        a.g = "G+"
                                                        something = a.a





                                                        share|improve this answer














                                                        The SimpleNamespace class could be used to create new attributes with setattr, or subclass SimpleNamespace and create your own function to add new attribute names (variables).



                                                        from types import SimpleNamespace

                                                        variables = "b":"B","c":"C"
                                                        a = SimpleNamespace(**v)
                                                        setattr(a,"g","G")
                                                        a.g = "G+"
                                                        something = a.a






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Sep 18 '17 at 0:03









                                                        lukess

                                                        73111318




                                                        73111318










                                                        answered Sep 17 '17 at 22:38









                                                        Bill Oldroyd

                                                        13114




                                                        13114




















                                                            up vote
                                                            3
                                                            down vote













                                                            I'm am answering the question: How to get the value of a variable given its name in a string?
                                                            which is closed as a duplicate with a link to this question.



                                                            If the variables in question are part of an object (part of a class for example) then some useful functions to achieve exactly that are hasattr, getattr, and setattr.



                                                            So for example you can have:



                                                            class Variables(object):
                                                            def __init__(self):
                                                            self.foo = "initial_variable"
                                                            def create_new_var(self,name,value):
                                                            setattr(self,name,value)
                                                            def get_var(self,name):
                                                            if hasattr(self,name):
                                                            return getattr(self,name)
                                                            else:
                                                            raise("Class does not have a variable named: "+name)


                                                            Then you can do:



                                                            v = Variables()
                                                            v.get_var("foo")



                                                            "initial_variable"




                                                            v.create_new_var(v.foo,"is actually not initial")
                                                            v.initial_variable



                                                            "is actually not initial"







                                                            share|improve this answer


























                                                              up vote
                                                              3
                                                              down vote













                                                              I'm am answering the question: How to get the value of a variable given its name in a string?
                                                              which is closed as a duplicate with a link to this question.



                                                              If the variables in question are part of an object (part of a class for example) then some useful functions to achieve exactly that are hasattr, getattr, and setattr.



                                                              So for example you can have:



                                                              class Variables(object):
                                                              def __init__(self):
                                                              self.foo = "initial_variable"
                                                              def create_new_var(self,name,value):
                                                              setattr(self,name,value)
                                                              def get_var(self,name):
                                                              if hasattr(self,name):
                                                              return getattr(self,name)
                                                              else:
                                                              raise("Class does not have a variable named: "+name)


                                                              Then you can do:



                                                              v = Variables()
                                                              v.get_var("foo")



                                                              "initial_variable"




                                                              v.create_new_var(v.foo,"is actually not initial")
                                                              v.initial_variable



                                                              "is actually not initial"







                                                              share|improve this answer
























                                                                up vote
                                                                3
                                                                down vote










                                                                up vote
                                                                3
                                                                down vote









                                                                I'm am answering the question: How to get the value of a variable given its name in a string?
                                                                which is closed as a duplicate with a link to this question.



                                                                If the variables in question are part of an object (part of a class for example) then some useful functions to achieve exactly that are hasattr, getattr, and setattr.



                                                                So for example you can have:



                                                                class Variables(object):
                                                                def __init__(self):
                                                                self.foo = "initial_variable"
                                                                def create_new_var(self,name,value):
                                                                setattr(self,name,value)
                                                                def get_var(self,name):
                                                                if hasattr(self,name):
                                                                return getattr(self,name)
                                                                else:
                                                                raise("Class does not have a variable named: "+name)


                                                                Then you can do:



                                                                v = Variables()
                                                                v.get_var("foo")



                                                                "initial_variable"




                                                                v.create_new_var(v.foo,"is actually not initial")
                                                                v.initial_variable



                                                                "is actually not initial"







                                                                share|improve this answer














                                                                I'm am answering the question: How to get the value of a variable given its name in a string?
                                                                which is closed as a duplicate with a link to this question.



                                                                If the variables in question are part of an object (part of a class for example) then some useful functions to achieve exactly that are hasattr, getattr, and setattr.



                                                                So for example you can have:



                                                                class Variables(object):
                                                                def __init__(self):
                                                                self.foo = "initial_variable"
                                                                def create_new_var(self,name,value):
                                                                setattr(self,name,value)
                                                                def get_var(self,name):
                                                                if hasattr(self,name):
                                                                return getattr(self,name)
                                                                else:
                                                                raise("Class does not have a variable named: "+name)


                                                                Then you can do:



                                                                v = Variables()
                                                                v.get_var("foo")



                                                                "initial_variable"




                                                                v.create_new_var(v.foo,"is actually not initial")
                                                                v.initial_variable



                                                                "is actually not initial"








                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited May 23 '17 at 12:10









                                                                Community

                                                                11




                                                                11










                                                                answered Nov 2 '16 at 15:53









                                                                patapouf_ai

                                                                6,15044284




                                                                6,15044284




















                                                                    up vote
                                                                    1
                                                                    down vote













                                                                    The consensus is to use a dictionary for this - see the other answers. This is a good idea for most cases, however, there are many aspects arising from this:



                                                                    • you'll yourself be responsible for this dictionary, including garbage collection (of in-dict variables) etc.

                                                                    • there's either no locality or globality for variable variables, it depends on the globality of the dictionary

                                                                    • if you want to rename a variable name, you'll have to do it manually

                                                                    • however, you are much more flexible, e.g.

                                                                      • you can decide to overwrite existing variables or ...

                                                                      • ... choose to implement const variables

                                                                      • to raise an exception on overwriting for different types

                                                                      • etc.


                                                                    That said, I've implemented a variable variables manager-class which provides some of the above ideas. It works for python 2 and 3.



                                                                    You'd use the class like this:



                                                                    from variableVariablesManager import VariableVariablesManager

                                                                    myVars = VariableVariablesManager()
                                                                    myVars['test'] = 25
                                                                    print(myVars['test'])

                                                                    # define a const variable
                                                                    myVars.defineConstVariable('myconst', 13)
                                                                    try:
                                                                    myVars['myconst'] = 14 # <- this raises an error, since 'myconst' must not be changed
                                                                    print("not allowed")
                                                                    except AttributeError as e:
                                                                    pass

                                                                    # rename a variable
                                                                    myVars.renameVariable('myconst', 'myconstOther')

                                                                    # preserve locality
                                                                    def testLocalVar():
                                                                    myVars = VariableVariablesManager()
                                                                    myVars['test'] = 13
                                                                    print("inside function myVars['test']:", myVars['test'])
                                                                    testLocalVar()
                                                                    print("outside function myVars['test']:", myVars['test'])

                                                                    # define a global variable
                                                                    myVars.defineGlobalVariable('globalVar', 12)
                                                                    def testGlobalVar():
                                                                    myVars = VariableVariablesManager()
                                                                    print("inside function myVars['globalVar']:", myVars['globalVar'])
                                                                    myVars['globalVar'] = 13
                                                                    print("inside function myVars['globalVar'] (having been changed):", myVars['globalVar'])
                                                                    testGlobalVar()
                                                                    print("outside function myVars['globalVar']:", myVars['globalVar'])


                                                                    If you wish to allow overwriting of variables with the same type only:



                                                                    myVars = VariableVariablesManager(enforceSameTypeOnOverride = True)
                                                                    myVars['test'] = 25
                                                                    myVars['test'] = "Cat" # <- raises Exception (different type on overwriting)





                                                                    share|improve this answer






















                                                                    • At first glance the long camelised imports made me think this was Java.
                                                                      – markroxor
                                                                      Feb 19 at 6:17














                                                                    up vote
                                                                    1
                                                                    down vote













                                                                    The consensus is to use a dictionary for this - see the other answers. This is a good idea for most cases, however, there are many aspects arising from this:



                                                                    • you'll yourself be responsible for this dictionary, including garbage collection (of in-dict variables) etc.

                                                                    • there's either no locality or globality for variable variables, it depends on the globality of the dictionary

                                                                    • if you want to rename a variable name, you'll have to do it manually

                                                                    • however, you are much more flexible, e.g.

                                                                      • you can decide to overwrite existing variables or ...

                                                                      • ... choose to implement const variables

                                                                      • to raise an exception on overwriting for different types

                                                                      • etc.


                                                                    That said, I've implemented a variable variables manager-class which provides some of the above ideas. It works for python 2 and 3.



                                                                    You'd use the class like this:



                                                                    from variableVariablesManager import VariableVariablesManager

                                                                    myVars = VariableVariablesManager()
                                                                    myVars['test'] = 25
                                                                    print(myVars['test'])

                                                                    # define a const variable
                                                                    myVars.defineConstVariable('myconst', 13)
                                                                    try:
                                                                    myVars['myconst'] = 14 # <- this raises an error, since 'myconst' must not be changed
                                                                    print("not allowed")
                                                                    except AttributeError as e:
                                                                    pass

                                                                    # rename a variable
                                                                    myVars.renameVariable('myconst', 'myconstOther')

                                                                    # preserve locality
                                                                    def testLocalVar():
                                                                    myVars = VariableVariablesManager()
                                                                    myVars['test'] = 13
                                                                    print("inside function myVars['test']:", myVars['test'])
                                                                    testLocalVar()
                                                                    print("outside function myVars['test']:", myVars['test'])

                                                                    # define a global variable
                                                                    myVars.defineGlobalVariable('globalVar', 12)
                                                                    def testGlobalVar():
                                                                    myVars = VariableVariablesManager()
                                                                    print("inside function myVars['globalVar']:", myVars['globalVar'])
                                                                    myVars['globalVar'] = 13
                                                                    print("inside function myVars['globalVar'] (having been changed):", myVars['globalVar'])
                                                                    testGlobalVar()
                                                                    print("outside function myVars['globalVar']:", myVars['globalVar'])


                                                                    If you wish to allow overwriting of variables with the same type only:



                                                                    myVars = VariableVariablesManager(enforceSameTypeOnOverride = True)
                                                                    myVars['test'] = 25
                                                                    myVars['test'] = "Cat" # <- raises Exception (different type on overwriting)





                                                                    share|improve this answer






















                                                                    • At first glance the long camelised imports made me think this was Java.
                                                                      – markroxor
                                                                      Feb 19 at 6:17












                                                                    up vote
                                                                    1
                                                                    down vote










                                                                    up vote
                                                                    1
                                                                    down vote









                                                                    The consensus is to use a dictionary for this - see the other answers. This is a good idea for most cases, however, there are many aspects arising from this:



                                                                    • you'll yourself be responsible for this dictionary, including garbage collection (of in-dict variables) etc.

                                                                    • there's either no locality or globality for variable variables, it depends on the globality of the dictionary

                                                                    • if you want to rename a variable name, you'll have to do it manually

                                                                    • however, you are much more flexible, e.g.

                                                                      • you can decide to overwrite existing variables or ...

                                                                      • ... choose to implement const variables

                                                                      • to raise an exception on overwriting for different types

                                                                      • etc.


                                                                    That said, I've implemented a variable variables manager-class which provides some of the above ideas. It works for python 2 and 3.



                                                                    You'd use the class like this:



                                                                    from variableVariablesManager import VariableVariablesManager

                                                                    myVars = VariableVariablesManager()
                                                                    myVars['test'] = 25
                                                                    print(myVars['test'])

                                                                    # define a const variable
                                                                    myVars.defineConstVariable('myconst', 13)
                                                                    try:
                                                                    myVars['myconst'] = 14 # <- this raises an error, since 'myconst' must not be changed
                                                                    print("not allowed")
                                                                    except AttributeError as e:
                                                                    pass

                                                                    # rename a variable
                                                                    myVars.renameVariable('myconst', 'myconstOther')

                                                                    # preserve locality
                                                                    def testLocalVar():
                                                                    myVars = VariableVariablesManager()
                                                                    myVars['test'] = 13
                                                                    print("inside function myVars['test']:", myVars['test'])
                                                                    testLocalVar()
                                                                    print("outside function myVars['test']:", myVars['test'])

                                                                    # define a global variable
                                                                    myVars.defineGlobalVariable('globalVar', 12)
                                                                    def testGlobalVar():
                                                                    myVars = VariableVariablesManager()
                                                                    print("inside function myVars['globalVar']:", myVars['globalVar'])
                                                                    myVars['globalVar'] = 13
                                                                    print("inside function myVars['globalVar'] (having been changed):", myVars['globalVar'])
                                                                    testGlobalVar()
                                                                    print("outside function myVars['globalVar']:", myVars['globalVar'])


                                                                    If you wish to allow overwriting of variables with the same type only:



                                                                    myVars = VariableVariablesManager(enforceSameTypeOnOverride = True)
                                                                    myVars['test'] = 25
                                                                    myVars['test'] = "Cat" # <- raises Exception (different type on overwriting)





                                                                    share|improve this answer














                                                                    The consensus is to use a dictionary for this - see the other answers. This is a good idea for most cases, however, there are many aspects arising from this:



                                                                    • you'll yourself be responsible for this dictionary, including garbage collection (of in-dict variables) etc.

                                                                    • there's either no locality or globality for variable variables, it depends on the globality of the dictionary

                                                                    • if you want to rename a variable name, you'll have to do it manually

                                                                    • however, you are much more flexible, e.g.

                                                                      • you can decide to overwrite existing variables or ...

                                                                      • ... choose to implement const variables

                                                                      • to raise an exception on overwriting for different types

                                                                      • etc.


                                                                    That said, I've implemented a variable variables manager-class which provides some of the above ideas. It works for python 2 and 3.



                                                                    You'd use the class like this:



                                                                    from variableVariablesManager import VariableVariablesManager

                                                                    myVars = VariableVariablesManager()
                                                                    myVars['test'] = 25
                                                                    print(myVars['test'])

                                                                    # define a const variable
                                                                    myVars.defineConstVariable('myconst', 13)
                                                                    try:
                                                                    myVars['myconst'] = 14 # <- this raises an error, since 'myconst' must not be changed
                                                                    print("not allowed")
                                                                    except AttributeError as e:
                                                                    pass

                                                                    # rename a variable
                                                                    myVars.renameVariable('myconst', 'myconstOther')

                                                                    # preserve locality
                                                                    def testLocalVar():
                                                                    myVars = VariableVariablesManager()
                                                                    myVars['test'] = 13
                                                                    print("inside function myVars['test']:", myVars['test'])
                                                                    testLocalVar()
                                                                    print("outside function myVars['test']:", myVars['test'])

                                                                    # define a global variable
                                                                    myVars.defineGlobalVariable('globalVar', 12)
                                                                    def testGlobalVar():
                                                                    myVars = VariableVariablesManager()
                                                                    print("inside function myVars['globalVar']:", myVars['globalVar'])
                                                                    myVars['globalVar'] = 13
                                                                    print("inside function myVars['globalVar'] (having been changed):", myVars['globalVar'])
                                                                    testGlobalVar()
                                                                    print("outside function myVars['globalVar']:", myVars['globalVar'])


                                                                    If you wish to allow overwriting of variables with the same type only:



                                                                    myVars = VariableVariablesManager(enforceSameTypeOnOverride = True)
                                                                    myVars['test'] = 25
                                                                    myVars['test'] = "Cat" # <- raises Exception (different type on overwriting)






                                                                    share|improve this answer














                                                                    share|improve this answer



                                                                    share|improve this answer








                                                                    edited Jun 9 '16 at 12:10

























                                                                    answered Jun 9 '16 at 11:47









                                                                    DomTomCat

                                                                    3,88212544




                                                                    3,88212544











                                                                    • At first glance the long camelised imports made me think this was Java.
                                                                      – markroxor
                                                                      Feb 19 at 6:17
















                                                                    • At first glance the long camelised imports made me think this was Java.
                                                                      – markroxor
                                                                      Feb 19 at 6:17















                                                                    At first glance the long camelised imports made me think this was Java.
                                                                    – markroxor
                                                                    Feb 19 at 6:17




                                                                    At first glance the long camelised imports made me think this was Java.
                                                                    – markroxor
                                                                    Feb 19 at 6:17










                                                                    up vote
                                                                    1
                                                                    down vote













                                                                    Please refer following example to create variables runtime. You can use globals().



                                                                    for i in range(3):
                                                                    globals() ['variable_'+str(i)] = i


                                                                    In the above example, I want to create three variables: variable_0, variable_1 and variable_2 at runtime with values 0,1 and 2 respectively.



                                                                    variable_0
                                                                    [Output]:0

                                                                    variable_1
                                                                    [Output]:1

                                                                    variable_2
                                                                    [Output]:2


                                                                    To access the value of variables created at runtime, you can use eval() method as follows:



                                                                    for i in range(3):
                                                                    globals() ['variable_'+str(i)] = i
                                                                    print('Variable Value:',eval('variable_'+str(i)))

                                                                    [Output]:
                                                                    Variable Value: 0
                                                                    Variable Value: 1
                                                                    Variable Value: 2





                                                                    share|improve this answer
























                                                                      up vote
                                                                      1
                                                                      down vote













                                                                      Please refer following example to create variables runtime. You can use globals().



                                                                      for i in range(3):
                                                                      globals() ['variable_'+str(i)] = i


                                                                      In the above example, I want to create three variables: variable_0, variable_1 and variable_2 at runtime with values 0,1 and 2 respectively.



                                                                      variable_0
                                                                      [Output]:0

                                                                      variable_1
                                                                      [Output]:1

                                                                      variable_2
                                                                      [Output]:2


                                                                      To access the value of variables created at runtime, you can use eval() method as follows:



                                                                      for i in range(3):
                                                                      globals() ['variable_'+str(i)] = i
                                                                      print('Variable Value:',eval('variable_'+str(i)))

                                                                      [Output]:
                                                                      Variable Value: 0
                                                                      Variable Value: 1
                                                                      Variable Value: 2





                                                                      share|improve this answer






















                                                                        up vote
                                                                        1
                                                                        down vote










                                                                        up vote
                                                                        1
                                                                        down vote









                                                                        Please refer following example to create variables runtime. You can use globals().



                                                                        for i in range(3):
                                                                        globals() ['variable_'+str(i)] = i


                                                                        In the above example, I want to create three variables: variable_0, variable_1 and variable_2 at runtime with values 0,1 and 2 respectively.



                                                                        variable_0
                                                                        [Output]:0

                                                                        variable_1
                                                                        [Output]:1

                                                                        variable_2
                                                                        [Output]:2


                                                                        To access the value of variables created at runtime, you can use eval() method as follows:



                                                                        for i in range(3):
                                                                        globals() ['variable_'+str(i)] = i
                                                                        print('Variable Value:',eval('variable_'+str(i)))

                                                                        [Output]:
                                                                        Variable Value: 0
                                                                        Variable Value: 1
                                                                        Variable Value: 2





                                                                        share|improve this answer












                                                                        Please refer following example to create variables runtime. You can use globals().



                                                                        for i in range(3):
                                                                        globals() ['variable_'+str(i)] = i


                                                                        In the above example, I want to create three variables: variable_0, variable_1 and variable_2 at runtime with values 0,1 and 2 respectively.



                                                                        variable_0
                                                                        [Output]:0

                                                                        variable_1
                                                                        [Output]:1

                                                                        variable_2
                                                                        [Output]:2


                                                                        To access the value of variables created at runtime, you can use eval() method as follows:



                                                                        for i in range(3):
                                                                        globals() ['variable_'+str(i)] = i
                                                                        print('Variable Value:',eval('variable_'+str(i)))

                                                                        [Output]:
                                                                        Variable Value: 0
                                                                        Variable Value: 1
                                                                        Variable Value: 2






                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Nov 20 at 19:32









                                                                        Sayali Sonawane

                                                                        5,87722434




                                                                        5,87722434




















                                                                            up vote
                                                                            0
                                                                            down vote













                                                                            Any set of variables can also be wrapped up in a class.
                                                                            "Variable" variables may be added to the class instance during runtime by directly accessing the built-in dictionary through __dict__ attribute.



                                                                            The following code defines Variables class, which adds variables (in this case attributes) to its instance during the construction. Variable names are taken from a specified list (which, for example, could have been generated by program code):



                                                                            # some list of variable names
                                                                            L = ['a', 'b', 'c']

                                                                            class Variables:
                                                                            def __init__(self, L):
                                                                            for item in L:
                                                                            self.__dict__[item] = 100

                                                                            v = Variables(L)
                                                                            print(v.a, v.b, v.c)
                                                                            #will produce 100 100 100





                                                                            share|improve this answer
























                                                                              up vote
                                                                              0
                                                                              down vote













                                                                              Any set of variables can also be wrapped up in a class.
                                                                              "Variable" variables may be added to the class instance during runtime by directly accessing the built-in dictionary through __dict__ attribute.



                                                                              The following code defines Variables class, which adds variables (in this case attributes) to its instance during the construction. Variable names are taken from a specified list (which, for example, could have been generated by program code):



                                                                              # some list of variable names
                                                                              L = ['a', 'b', 'c']

                                                                              class Variables:
                                                                              def __init__(self, L):
                                                                              for item in L:
                                                                              self.__dict__[item] = 100

                                                                              v = Variables(L)
                                                                              print(v.a, v.b, v.c)
                                                                              #will produce 100 100 100





                                                                              share|improve this answer






















                                                                                up vote
                                                                                0
                                                                                down vote










                                                                                up vote
                                                                                0
                                                                                down vote









                                                                                Any set of variables can also be wrapped up in a class.
                                                                                "Variable" variables may be added to the class instance during runtime by directly accessing the built-in dictionary through __dict__ attribute.



                                                                                The following code defines Variables class, which adds variables (in this case attributes) to its instance during the construction. Variable names are taken from a specified list (which, for example, could have been generated by program code):



                                                                                # some list of variable names
                                                                                L = ['a', 'b', 'c']

                                                                                class Variables:
                                                                                def __init__(self, L):
                                                                                for item in L:
                                                                                self.__dict__[item] = 100

                                                                                v = Variables(L)
                                                                                print(v.a, v.b, v.c)
                                                                                #will produce 100 100 100





                                                                                share|improve this answer












                                                                                Any set of variables can also be wrapped up in a class.
                                                                                "Variable" variables may be added to the class instance during runtime by directly accessing the built-in dictionary through __dict__ attribute.



                                                                                The following code defines Variables class, which adds variables (in this case attributes) to its instance during the construction. Variable names are taken from a specified list (which, for example, could have been generated by program code):



                                                                                # some list of variable names
                                                                                L = ['a', 'b', 'c']

                                                                                class Variables:
                                                                                def __init__(self, L):
                                                                                for item in L:
                                                                                self.__dict__[item] = 100

                                                                                v = Variables(L)
                                                                                print(v.a, v.b, v.c)
                                                                                #will produce 100 100 100






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Aug 11 '17 at 21:13









                                                                                Alexey Rodimov

                                                                                495




                                                                                495




















                                                                                    up vote
                                                                                    0
                                                                                    down vote













                                                                                    Use globals()



                                                                                    You can actually assign variables to global scope dynamically, for instance, if you want 10 variables that can be accessed on a global scope i_1, i_2 ... i_10:



                                                                                    for i in range(10):
                                                                                    globals()['i_'.format(i)] = 'a'


                                                                                    This will assign 'a' to all of these 10 variables, of course you can change the value dynamically as well. All of these variables can be accessed now like other globally declared variable:



                                                                                    >>> i_5
                                                                                    'a'





                                                                                    share|improve this answer
























                                                                                      up vote
                                                                                      0
                                                                                      down vote













                                                                                      Use globals()



                                                                                      You can actually assign variables to global scope dynamically, for instance, if you want 10 variables that can be accessed on a global scope i_1, i_2 ... i_10:



                                                                                      for i in range(10):
                                                                                      globals()['i_'.format(i)] = 'a'


                                                                                      This will assign 'a' to all of these 10 variables, of course you can change the value dynamically as well. All of these variables can be accessed now like other globally declared variable:



                                                                                      >>> i_5
                                                                                      'a'





                                                                                      share|improve this answer






















                                                                                        up vote
                                                                                        0
                                                                                        down vote










                                                                                        up vote
                                                                                        0
                                                                                        down vote









                                                                                        Use globals()



                                                                                        You can actually assign variables to global scope dynamically, for instance, if you want 10 variables that can be accessed on a global scope i_1, i_2 ... i_10:



                                                                                        for i in range(10):
                                                                                        globals()['i_'.format(i)] = 'a'


                                                                                        This will assign 'a' to all of these 10 variables, of course you can change the value dynamically as well. All of these variables can be accessed now like other globally declared variable:



                                                                                        >>> i_5
                                                                                        'a'





                                                                                        share|improve this answer












                                                                                        Use globals()



                                                                                        You can actually assign variables to global scope dynamically, for instance, if you want 10 variables that can be accessed on a global scope i_1, i_2 ... i_10:



                                                                                        for i in range(10):
                                                                                        globals()['i_'.format(i)] = 'a'


                                                                                        This will assign 'a' to all of these 10 variables, of course you can change the value dynamically as well. All of these variables can be accessed now like other globally declared variable:



                                                                                        >>> i_5
                                                                                        'a'






                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Nov 27 at 15:34









                                                                                        Rocky Li

                                                                                        2,6391315




                                                                                        2,6391315




















                                                                                            up vote
                                                                                            -1
                                                                                            down vote













                                                                                            a = 'hi'
                                                                                            # the expression below is a dynamic way of saying: b = 'by'
                                                                                            locals()['b'] = 'by'

                                                                                            print(a)
                                                                                            # 'hi'
                                                                                            print(b)
                                                                                            # 'by'





                                                                                            share|improve this answer


















                                                                                            • 1




                                                                                              Try to add details while answering.
                                                                                              – M.A.K. Ripon
                                                                                              Oct 7 at 17:12














                                                                                            up vote
                                                                                            -1
                                                                                            down vote













                                                                                            a = 'hi'
                                                                                            # the expression below is a dynamic way of saying: b = 'by'
                                                                                            locals()['b'] = 'by'

                                                                                            print(a)
                                                                                            # 'hi'
                                                                                            print(b)
                                                                                            # 'by'





                                                                                            share|improve this answer


















                                                                                            • 1




                                                                                              Try to add details while answering.
                                                                                              – M.A.K. Ripon
                                                                                              Oct 7 at 17:12












                                                                                            up vote
                                                                                            -1
                                                                                            down vote










                                                                                            up vote
                                                                                            -1
                                                                                            down vote









                                                                                            a = 'hi'
                                                                                            # the expression below is a dynamic way of saying: b = 'by'
                                                                                            locals()['b'] = 'by'

                                                                                            print(a)
                                                                                            # 'hi'
                                                                                            print(b)
                                                                                            # 'by'





                                                                                            share|improve this answer














                                                                                            a = 'hi'
                                                                                            # the expression below is a dynamic way of saying: b = 'by'
                                                                                            locals()['b'] = 'by'

                                                                                            print(a)
                                                                                            # 'hi'
                                                                                            print(b)
                                                                                            # 'by'






                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Oct 8 at 3:09

























                                                                                            answered Oct 7 at 16:45









                                                                                            Sam Arthur Gillam

                                                                                            644




                                                                                            644







                                                                                            • 1




                                                                                              Try to add details while answering.
                                                                                              – M.A.K. Ripon
                                                                                              Oct 7 at 17:12












                                                                                            • 1




                                                                                              Try to add details while answering.
                                                                                              – M.A.K. Ripon
                                                                                              Oct 7 at 17:12







                                                                                            1




                                                                                            1




                                                                                            Try to add details while answering.
                                                                                            – M.A.K. Ripon
                                                                                            Oct 7 at 17:12




                                                                                            Try to add details while answering.
                                                                                            – M.A.K. Ripon
                                                                                            Oct 7 at 17:12





                                                                                            protected by Bhargav Rao Apr 21 '16 at 15:03



                                                                                            Thank you for your interest in this question.
                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                            Popular posts from this blog

                                                                                            Top Tejano songwriter Luis Silva dead of heart attack at 64

                                                                                            政党

                                                                                            天津地下鉄3号線