How can you dynamically create variables via a while loop?

Noah R picture Noah R · Feb 18, 2011 · Viewed 340.8k times · Source

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

Answer

JoshAdel picture JoshAdel · Feb 18, 2011

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 new 'collections' module that might be applicable:

http://docs.python.org/dev/library/collections.html