On Tue, Mar 25, 2014 at 1:04 AM, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: >> But which of these is truly more readable? >> >> squares = [] >> for n in range(30): >> squares.append(n * n) >> >> squares = [n * n for n in range(30)] > > Readable for whom? > > List comprehension syntax is often completely obscure to beginners. A > beginner would say that the explicit for-loop is more readable. > > Actually, a *real* beginner, whose main programming experience before > Python was Pascal, would probably even say that the first example was an > unreadable mess. What's range(30)? What's this ".append" business? What > does [] mean? I know this because I was this beginner, once. The first > few times I tried reading Python code, I couldn't make head or tail of > it. "for" I recognised, because it was the same keyword as Pascal and > Hypertalk use. Pretty much everything else might as well have been > Bulgarian.
Actually, that's a very good point. Python's for loop is more often called a foreach loop in other languages, and Python completely lacks any concept of a "classic" iteration-over-integer for loop. That is a point of confusion. However, that's going to come up on both branches, so it's not really a mark against either. Incidentally, I've often modified my loop counter, in C or REXX or any other language. About the only situation where I actually miss it in Python, though, is iterating over a list and mutating the list on the way through; and even that can often be done in other ways (maybe a list comp, filtering out some of the elements?). It's amazing how something can be so utterly fundamental (I mean, come ON! Who can imagine a language with no equivalent of the basic "do i=1 to 10" (REXX) or "for (int i=0;i<10;++i)" (C++) loop???) and yet so dispensable. ChrisA -- https://mail.python.org/mailman/listinfo/python-list