Noah R Noah R - 6 months ago 26
Python Question

How can you dynamically create variables via a while loop?

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


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: