Do this as a list comprehension?

Paul Miller none at this.time
Sat Jun 7 12:21:59 CEST 2008


On Fri, 06 Jun 2008 18:01:45 -0700, Mensanator wrote:


> What happens if your iterables aren't the same length?

I chose not to consider that case, since they were the same length in the 
original post.  Based on the variable names, it seemed reasonable that 
there would always be a 1-to-1 correspondence between elements of each 
list.  However, if you do

score_costs = [(base_scores[i], score_costs[i]) for i in range (min (len 
(base_scores), len (score_costs))]

then you get exactly what you would get using zip.  That's one heck of a 
long line, though, hence my earlier comment:

>> But, I'd rather just use zip. :-)
> 
> And with zip() you won't get an error, but it won't be correct, either.

If it doing what zip() does makes sense, then just use zip().  Otherwise, 
check for the case where the iterables are of different length, and do 
the appropriate thing (raise an error, pad the shorter one, whatever).

-- 
code.py: a blog about Python.  http://pythonista.wordpress.com
** Posted from http://www.teranews.com **



More information about the Python-list mailing list