Simple exercise

Rick Johnson rantingrickjohnson at gmail.com
Mon Mar 14 10:35:41 EDT 2016


On Thursday, March 10, 2016 at 8:04:04 PM UTC-6, Mark Lawrence wrote:
> On 11/03/2016 01:45, BartC wrote:
> > [...]
> > Any other way of traversing two lists in parallel?
> >
>
> Use zip()

Sure, the zip function is quite handy, but it can produce
subtle bugs when both sequences are not of the same length.
Consider the following:

# BEGIN INTERACTIVE SESSION
>>> a = [1,2,3]
>>> b = list('abcde')
>>> for _ in zip(a, b):
...     print(_)
(1, 'a')
(2, 'b')
(3, 'c')
# END INTERACTIVE SESSION

Hey kids, the letter of the day is "e" , and the noun of the
day is "ether", and the verb of the day is, you guessed it:
"evaporate"!

I would strongly warn anyone against using the zip function
unless they are absolutely, one hundred percent, not
guilty... urm, oops, sorry to steal your line OJ. And BTW,
did you ever find your wife's killer? But i digress.

I meant to say: absolutely, one hundred percent *SURE*, that
both sequences are of the same length, or, absolutely one
hundred percent *SURE*, that dropping values is not going to
matter. For that reason, i avoid the zip function like the
plague. I would much rather get an index error, than let an
error pass silently.

PS: Hmm, why does that last sentence have such a familiar
"ring" to it?



More information about the Python-list mailing list