Noah R Noah R - 1 year ago 62
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?

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download