[Tutor] Q?
Daniel Yoo
dyoo@hkn.EECS.Berkeley.EDU
Thu, 31 Aug 2000 21:23:33 -0700 (PDT)
On Fri, 1 Sep 2000, deng wei wrote:
> The Python said this is wrong.But I think it's right.Why?
>
> # The while practice:
> a=['hello','world','i','am','a','worker']
> i=0
> while i<len(a):
> b[i]=a[len(a)-i]
> i=i+1
> print b
I'm guessing that this piece of code reverses the order of list 'a', and
places it into list 'b'. This would work, except that we haven't sized
'b' yet as a new list. Try it on the interpreter:
###
>>> a = ['hello', 'world', 'i', 'am', 'a', 'worker']
>>> i = 0
>>> while i < len(a):
... b[i] = a[len(a) - i]
... i = i + 1
...
Traceback (innermost last):
File "<stdin>", line 2, in ?
IndexError: list index out of range
###
To fix this, we need to properly set b to a list of equal size to
a. Here's one quick way of doing it:
###
>>> b = list(range(len(a)))
>>> b
[0, 1, 2, 3, 4, 5]
###
I create a tuple 'b' of size 'len(a)', and convert it to a list, so that
we can change elements of b. Afterwards, we should be ok:
###
>>> i = 0
>>> while i < len(a):
... b[i] = a[len(a) - i]
... i = i + 1
...
Traceback (innermost last):
File "<stdin>", line 2, in ?
IndexError: list index out of range
###
Hmm... I spoke too soon! Let's think about this. When i=0, then we try
to execute:
b[i] = a[5 - 0]
Ah! That's off the list! We can read from a[0], a[1], a[2], ..., a[4],
but not a[5]. This is why we're getting the IndexError.
The solution is to subtract 1 from the offset. If we do this, then the
loop will go through through b[4], b[3], ..., b[0].
###
b[i] = a[len(a) - i - 1]
###
should be the corrected line.