iterating over lists

Malcolm Tredinnick malcolm at
Sat Jun 2 12:59:50 EDT 2001

On Sat, Jun 02, 2001 at 10:04:06AM -0500, John Hunter wrote:
> I have three lists of equal size: list1, list2 and list3.
> What I want but doesn't work:
>   for (x1, x2, x3) in (list1, list2, list3):
>      print x1, x2, x3
> I know I can do it by keeping a index count variable: 
>      N = len(list1)
>      for i in range(1,N):
>          print list1[i], list2[i], list3[i]
> but am wondering if there is way to create a tuple of named variables
> as in the (x1, x2, x3) example above.

This does what you want:

	for x1, x2, x3 in map(None, list1, list2, list3):
		print x1, x2, x3
(a nice use of map to remember).

> One final question:  If I do:
>      for i in range( 1, len(list1) ):
>          print list1[i], list2[i], list3[i]
> I assume the len(list1) call will only be evaluated once.  Is this
> correct?

Yes, that's correct. You can check this by doing something like:

	l = [1, 2, 3]
	for i in range(len(l)):
		print i

and notice that it only goes through 3 times, despite the growth in


A day without sunshine is like, night.

More information about the Python-list mailing list