[Tutor] Final review
Steven D'Aprano
steve at pearwood.info
Thu May 8 15:30:49 CEST 2014
On Wed, May 07, 2014 at 08:49:11PM -0700, Scott W Dunning wrote:
[...]
> > >>> greeting [len(greeting)]
> >
> > It is trying to access the character at the position "11", where the
> > string "Hello world" doesn't contain any value in the index "11" and
> > the maximum index is 10. So it throws the following error.
>
> I think this is where I am getting confused. I guess I don’t
> understand why/how it’s trying to access the character at the index
> 11?
The value of greeting is "Hello world". So let's write it out, showing
the index of each character. Remember that Python starts counting from
zero, not one:
Index 0: H
Index 1: e
Index 2: l
Index 3: l
Index 4: o
Index 5: space
Index 6: w
Index 7: o
Index 8: r
Index 9: l
Index 10: d
So the indexes start from 0, and go up to 10. How many characters are
there? Count them, and you get 11. Which makes sense: one character per
index, there are at least ten indexes (1 through 10), plus one extra
(index 0) makes 11. So the length of the string is 11, but the highest
index is 10.
So greeting[0] gives "H", greeting[1] gives "e", greeting[2] gives "l",
and so on, until you get to greeting[10] which gives "d", and
greeting[len(greeting)] => greeting[11] which is an error.
--
Steven
More information about the Tutor
mailing list