On Thu, Mar 15, 2012 at 10:27 PM, Kiuhnm <kiuhnm03.4t.yahoo...@mail.python.org> wrote: > On 3/15/2012 11:50, Chris Angelico wrote: >> I'll do a list comp, because they lend themselves well to one-liners. >> what_am_i = '\n'.join(["%X\t%c"%(i,i) for i in range(128)]) > > > A few conjectures: > 1) '\n' is an object and join one of its methods; > 2) [...] is a list comprehension; > 3) that 'for' suggests that range isn't (or doesn't return) a list but an > iterator; > 4) points 2 and 3 suggest that [...] builds a list (or array?) by querying > an iterator. > 5) "%X\t%"(i,i) is probably equivalent to the C-like Perl's > sprintf("%X\t%c", i, i) > > So what_am_i is a simple ASCII table.
Correct. Actually, there's a few differences between Python 2 and 3; in Py2, range() returns a list, but in Py3 an iterable object. But 'for' will happily iterate over a list. >> Okay, that one also uses printf formatting, which may be a smidge >> obscure. Here's a simpler example: >> >> what_am_i = [x*x for x in range(11)] > > what_am_i = 0, 1, 4, 9, ..., 100 Correct again. > Your first example suggests that range(n) is a sequence iterator which > returns, if queried n times, > 0,...,n-1 > (which is a bit counterintuitive, IMHO). It's a little odd, perhaps, if seen in a vacuum. But everything counts from zero - list indices, etc - so it makes sense for range(len(lst)) to return indices valid for lst. List comps are pretty readable if you know how programming languages work. Python need not be readable by everyone and his grandmother, and it does a fairly good job of being grokkable to someone who has a few ranks in Coding. (Yeah, I'm a D&D nerd. ) ChrisA -- http://mail.python.org/mailman/listinfo/python-list