[Python] Variable variables?

Martin Kelly aomighty at gmail.com
Sun Mar 18 11:23:05 PDT 2007


If it's the second example, eval will work but there's usually cleaner 
ways to do it... I remember needing it once but I replaced it with 
something more understandable.

Bob Miller wrote:
> Rob Hudson wrote:
> 
>> Let's say I have 3 lists: list1, list2, list3
>>
>> And I want to write a loop to do something to each list.  I want to do 
>> something like this:
>>
>> 	for i in range(3):
>> 		myloop = "loop" + str(i)
>> 		# Do something to myloop, but myloop the interpretted
>> 		# variable, not myloop the string
>>
>> 1) Can python do this?
>>
>> 2) Is there a better way to handle this same idea another way?
> 
> Is this what you're asking for?
> 
> 	for l in (list1, list2, list3):
> 	    do_something_to(l)
> 
> Or do you need to construct the name?
> 
> 	for i in range(1, 4):
> 	    l = eval('list%d' % i)
> 	    do_something_to(l)
> 


More information about the Python mailing list