[Tutor] redundant function ( or, I need advice about cleaning up my code )

Kent Johnson kent_johnson at skillsoft.com
Sun Oct 31 04:03:50 CET 2004

That's exactly what the builtin function zip() does - it makes a list 
containing matched elements from each of the lists passed as arguments:
 >>> l1 = [1,2,3,4]
 >>> l2 = ['a', 'b', 'c', 'd']
 >>> zip(l1, l2)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
 >>> for number, letter in zip(l1, l2):
...   print number, letter
1 a
2 b
3 c
4 d

If you want to iterate a single list, but you need the index for some 
reason, you can use enumerate():
 >>> for i, item in enumerate(l2):
...   print i, item
0 a
1 b
2 c
3 d

enumerate() returns an iterator so if you want a list you have to ask for 
it explicitly:
 >>> list(enumerate(l2))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]


At 02:47 AM 10/31/2004 +0000, Max Noel wrote:

>On Oct 31, 2004, at 02:23, Morgan Meader wrote:
>>I did it that way because I had more than one list I was looking at. Is 
>>there another way to have the index so I can get values that match up by 
>>index on multiple lists?
>         Mmh... I don't think there's a built-in way to do that, but you 
> can create a custom iterator that will do the job. (iterators are another 
> great thing in Python, Ruby and Java)

More information about the Tutor mailing list