Alan Gauld wrote: > On 03/04/12 15:54, Khalid Al-Ghamdi wrote: > >> dom="".join(choice(lc) for j in range (dlen)) >> >> how does the interpreter know what "j" is supposed to refer to when it >> was not mentioned prior? > > In Python variables are defined by using them. > > In the code below you have i used in a for loop, even though not > mentioned before. j is similarly being used in the generator expression > for loop: > > choice(lc) for j in range (dlen) > > unwraps to: > > dummy = [] > for j in range(dlen): > dummy.append(choice(lc))
An interesting aspect of these "generator expressions" is that they are "lazy", they deliver only as many items as necessary. >>> numbers = (n for n in range(1000)) >>> next(numbers) 0 >>> next(numbers) 1 >>> any(n>10 for n in numbers) True >>> next(numbers) 12 >>> any(n<10 for n in numbers) False >>> next(numbers) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration The StopIteration hints that we have consumed all numbers. We were already at 13 when we asked for a number < 10; therefore the complete rest from 13 to 999 was scanned in vain. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor