Q: looping with two counter variables through a list

Emile van Sebille emile at fenx.com
Wed Dec 13 10:42:11 EST 2000


How about:

for i in range(0,len(mylist),2):
     a,b = mylist[i], mylist[i+1]

with approprite trapping for short lists.

Emile van Sebille
emile at fenx.com

Harald Kirsch wrote:

> In Tcl I can write
> 
>   set mylist {0 1 2 3 4 5}
>   foreach {a b} $mylist {
>     puts $a
>   }
> 
> to print the even numbers of $mylist. Obviously
> 
>    mylist = [0, 1, 2, 3, 4, 5]
>    for a,b in mylist:
>      print a
> 
> does not work (ValueError: unpack sequence of wrong size). 
> 
> What is Python's idiom for running with more than one variable through
> a flat list?
> 
>   Harald Kirsch




More information about the Python-list mailing list