Sep-13-2019, 01:02 AM
This isn't technically homework, as I'm working my own way through through a beginner's Python book rather than taking a course, but it seemed like the most appropriate thread for my question. If I'm out of line, please let me know and I won't make the mistake again.
Anyhow, I'm confused about an apparent conflict between the book's explanation of negative list indices and its subsequent use of said indices. The book is https://automatetheboringstuff.com/#toc . It's nice and clear, so I'm very happy with it, but am up against a roadblock on this one issue.
Here's the problem: I'm on the lists chapter right now, and it says "The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last index in a list, and so on." It then gives the following example list...
OK, so far so good. Everything's consistent. But then the book moves on to slices, and using the exact same example list that has elephant as its fourth (last) item, gives the following example:
Anyhow, I'm confused about an apparent conflict between the book's explanation of negative list indices and its subsequent use of said indices. The book is https://automatetheboringstuff.com/#toc . It's nice and clear, so I'm very happy with it, but am up against a roadblock on this one issue.
Here's the problem: I'm on the lists chapter right now, and it says "The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last index in a list, and so on." It then gives the following example list...
spam = ['cat', 'bat', 'rat', 'elephant']...and says that spam[-1] refers to the last value, 'elephant'.
OK, so far so good. Everything's consistent. But then the book moves on to slices, and using the exact same example list that has elephant as its fourth (last) item, gives the following example:
>>> spam[0:-1] ['cat', 'bat', 'rat']So how come "elephant" isn't included at the end? Shouldn't the result be ['cat', 'bat', 'rat', 'elephant']? Because if -1 always refers to the final list item, a result of ['cat', 'bat', 'rat'] doesn't make sense--to me, anyway. What am I missing?