[Tutor] Tuple iteration index

Kent Johnson kent_johnson at skillsoft.com
Wed Oct 20 22:08:56 CEST 2004


use the built-in function enumerate. enumerate(aList) returns an iterator 
that yields tuples of (index, value):
 >>> aTuple = ( [0.2, 0.8, 0], [0.8, 0.8, 0], [0.8,0.2, 0], [0.2, 0.2, 0] )
 >>> for i, aList in enumerate(aTuple):
...   print i, aList
...
0 [0.20000000000000001, 0.80000000000000004, 0]
1 [0.80000000000000004, 0.80000000000000004, 0]
2 [0.80000000000000004, 0.20000000000000001, 0]
3 [0.20000000000000001, 0.20000000000000001, 0]

You could also use aTuple.find(aList) but if you are iterating anyway 
enumerate() is better.

Kent


At 09:44 PM 10/20/2004 +0100, Bernard Lebel wrote:
>Hello,
>
>Let say I have a tuple of lists:
>
>aTuple = ( [0.2, 0.8, 0], [0.8, 0.8, 0], [0.8,0.2, 0], [0.2, 0.2, 0] )
>
>Now I wish to perform an iteration over this list.
>If I use something like:
>
>for aList in aTuple:
>
>I get a new item (in this case a list) at each line. This is fine, but I
>also need to know the index of that item in the tuple.
>
>for aList in aTuple:
>     print aList
>     # something like
>     print aTuple(aList.index)
>
>
>How do you do that?
>
>Thanks
>Bernard
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list