The chapter explains, but stepper shows.
|A = [ 2**i - 1 for i in range(10) ]|
|B = [ w for w in ("one","two","three") ]|
|v = ("over","to","you")|
|C = [ len(w) for w in v ]|
|x = [100,1000,500,600]|
|E = [ x[i+1]-x[i] for i in range(len(x)-1) ]|
The last one, using
k[i+1] is an idiom of programming.
Instead of directly accessing items in a sequence,
the comprehension uses index numbers. Because the
term in the comprehension has
it is important that the range of index values
stop just one short of last (so that i+1 will not
be an error).
Python version 2 makes visible the name of the comprehension item, even after the comprehension is finished. Python 3 remedies this situation. You might see in the example above that names w and i are each used in two comprehensions, and different values are given for these two names during the stepper run of the code. This can actually be considered a bug in the way that Python 2 behaves (the stepper uses Python 2). Please ignore this aspect of list comprehension in Python 2, though be mindful and do not use a temporary name in a comprehension expression that your program will define elsewhere to have some value.