[Python] Variable variables?

Bob Miller kbob at jogger-egg.com
Sun Mar 18 11:10:42 PDT 2007


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)

-- 
Bob Miller                              K<bob>
                                        kbob at jogger-egg.com


More information about the Python mailing list