Do this as a list comprehension?

Mensanator mensanator at aol.com
Sat Jun 7 19:24:23 CEST 2008


On Jun 7, 5:21�am, Paul Miller <n... at this.time> wrote:
> 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,

That's a bad habit to teach a newbie, isn't it?

> since they were the same length in the
> original post. �

The issue I'm stressing is HOW they got to be
the same size. If I was teaching programming
and the OP turned in that example, I would mark
him down. Not because he got the answer wrong.
Not because he used zip. Not because he failed
to use enumerate or itertools. But because he
hardcoded the array bounds and THAT'S the lesson
the OP should take away from this.

> Based on the variable names, it seemed reasonable that
> there would always be a 1-to-1 correspondence between
> elements of each list. �

Yes, reasonable at the time. But this is Python,
not C. Lists can change size under program control,
a feature that's extremely useful. But there's a
price for that usefulness. Practices that made
sense in C (define a constant to set array bounds)
aren't transportable over to systems that simply
don't have the restrictions that require those
practices.

> 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. �

And if the iterables change size dynamically, you
could get either a crash due to index out of range
or else silently a wrong answer.

> That's one heck of a
> long line, though, hence my earlier comment:

I have no problem telling the OP this method.
But I think you should warn him about potential
problems.

Surely you didn't intend to leave him to twist
in the wind so that he learns a thing or two
when his programs crash?

>
> >> 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).

That's all I'm suggesting. Along with pointing out
that enumerate or itertools can do this for him.

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




More information about the Python-list mailing list