Search code examples
pythonvariables

How can you dynamically create variables?


I want to create variables dynamically in Python. Does anyone have any creative means of doing this?


Solution

  • Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.

    a = {}
    k = 0
    while k < 10:
        # dynamically create key
        key = ...
        # calculate value
        value = ...
        a[key] = value 
        k += 1
    

    There are also some interesting data structures in the collections module that might be applicable.