simultaneous iteration of lists
Oren Tirosh
oren-py-l at hishome.net
Wed Jul 17 07:11:52 EDT 2002
On Thu, Jul 18, 2002 at 02:24:46AM +1000, Dave Harrison wrote:
> Evenin' all,
>
> Looking for advice on simultaneous iteration of two lists.
>
> I have two lists of equal length (guaranteed) , and I want to iterated over both at the same time without having to write myself a little counter thingo cause it seems slightly unpythonic.
> Both lists are generated by seperate functions which get their input from seperate sources so using a dictionary isnt an option either.
>
> The syntax that is in the back of my brain looks something like
>
> for i,j in list1,list2:
> print i
> print j
>
> But this gives me the error :
>
> ValueError: unpack list of wrong size
I see that a few people answered and told you to use zip. But in case you
want to know what the code you wrote actually tries to do:
(list1, list2) is a tuple with two lists as elements. The loop tries to
iterate over this tuple and unpack each element into i and j. This will
only work if the lists have exactly 2 items.
>>> list1=[1,2]
>>> list2=['a','b']
>>> for i,j in list1,list2:
... print i
... print j
...
1
2
'a'
'b'
Using zip(list1, list2) will produce the result you were probably expecting:
1
'a'
2
'b'
Oren
More information about the Python-list
mailing list