Slicing Lists - end index

So - why is the end index one more than the last index that we want to include?

This has me stumped, I guess I could just accept it and move on but it bothers me!

In the example given:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
sublist = letters[1:6]
print(sublist)

would yield:

['b', 'c', 'd', 'e', 'f']

But why 6 when ‘g’ is in the sixth index?

It is a numbering convention in many (nearly all?) computer languages, and, yes, you could just accept it and move on, but consider: what if you didn’t know how long the list was?

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
sublist = letters[1:len(letters)]   # no "magic numbers" needed!
print(sublist)

# prints ['b', 'c', 'd', 'e', 'f', 'g']

If you haven’t learned the range() function yet, you soon will, and you will note a very similar numbering convention.

2 Likes

so I’m a hardware engineer and have no issue with numbering systems starting at zero, I’m just stumped with this particular example - logically:

letters [1:6]

would yield:

['b', 'c', 'd', 'e', 'f', 'g']

Well, the example I showed - that the length of the list is compatible with thart second index - is enough for me, but between the two of us, we have only two votes against many decades of computer programming syntax.

So, better get used to it. Having learned and used the rule for awhile, the “logic” will look a bit different to you.

… or not: your call.

2 Likes

I appreciate your help, I’m just trying to understand this particular syntax :+1:

Your

letters[1:len(letters)]

example returns

['b', 'c', 'd', 'e', 'f', 'g']

as I would expect. In the exercise

letters[1:6]

returns

['b', 'c', 'd', 'e', 'f']

that’s my struggle here…

1 Like

Hey @analogue-anomaly

Good question, I think it is/was explained why this happens in the Python 2 material. Not sure whether it’s also in the Python 3 stuff.

Anyway, please refer to the Python Docs, specifically note 4 under Common Sequence Operations.

s[i:j]
slice of s from i to j
(3)(4)

  1. If i or j is negative, the index is relative to the end of sequence s : len(s) + i or len(s) + j is substituted. But note that -0 is still 0 .
  2. The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j . If i or j is greater than len(s) , use len(s) . If i is omitted or None , use 0 . If j is omitted or None , use len(s) . If i is greater than or equal to j , the slice is empty.

Hope that explains why you’re seeing that behaviour. :slight_smile:

3 Likes

Yes, because len(letters) is 7, not 6. You can always make use of that without needing to count anything. The length of the list will always give you the correct second index for a slice, or when using range().

3 Likes

Thanks again guys - I found this useful thread also, and I think its finally sinking in :+1:

2 Likes