If you absolutely have to, you could use locals()
to access local variables by a dynamic name (or globals()
for that matter).
For example:
foo0 = 'a'
foo1 = 'b'
foo2 = 'c'
for i in range(3):
name = 'foo%s' % i
value = locals().get(name)
print value
However, for locals()
this should be considered read only use. Modifying values in locals()
may seem to work in the interactive interpreter, but is unreliable. (Modifying values in globals()
is reliable as far as I know, but I'd strongly advise doing that in production code.)
If the dynamic names you want to use are attributes on objects however, you can use getattr(obj, name)
and setattr(obj, name, value)
, which are equivalent to value = obj.foo
and obj.foo = value
respectively. Those are "safe" and would work reliably. However, because it makes code very hard to read and understand without running it, they should be used sparingly for this purpose.