On Thu, 15 Mar 2012 20:54:30 +0000, Arnaud Delobelle wrote: > On 15 March 2012 00:27, Chris Angelico <ros...@gmail.com> wrote: >> On Thu, Mar 15, 2012 at 10:54 AM, Arnaud Delobelle <arno...@gmail.com> >> wrote: >>> I don't know this book and there may be a pedagogical reason for the >>> implementation you quote, but pairwise_sum is probably better >>> implemented in Python 3.X as: >>> >>> def pairwise_sum(list1, list2): >>> return [x1 + x2 for x1, x2 in zip(list1, list2)] >> >> Okay, here's something for debate. >> >> Should the readability of a language be gauged on the basis of its >> standard library, or should you be comparing actual code? > > But here's the code posted by the OP: > > --- Python --- > def pairwise_sum(list1, list2): > result = [] > for i in range(len(list1)): > result.append(list1[i] + list2[i]) > return result > --- --- > > The code I posted uses one builtin function (zip), the code posted by > the OP uses two (range and len). Neither uses the standard library.
For beginners, code using range and len is MUCH easier to understand than code using zip. len is obviously short for length, and range (at least in the one-argument version) is simple to explain. But zip? To understand zip, you need to have a good concept of iteration in your head. When writing for beginners, you can't assume that. For beginners, the most idiomatic code is not necessarily the simplest code. I would never start beginners with a list comprehension: result = [a+b for a,b in zip(list1, list2)] which is likely to be just incomprehensible jargon. You need to understand the syntax, which may not be obvious even to people with a mathematics background. (List comps are copied from Haskell, where they derive their syntax from mathematicians' set notation.) You need to understand zip, which requires having a good mental model of element-wise iteration. Although it is longer and less idiomatic, the Python1.5-ish result = [] for i in range(len(list1)): result.append(list1[i] + list2[i]) is likely to be simpler to understand. The downside is that experienced programmers may roll their eyes at how you are dumbing down the code, or worse, accusing you of deliberately misrepresenting the language. -- Steven -- http://mail.python.org/mailman/listinfo/python-list