0

I'm a beginner to Python, and recently I've gotten to the point of learning about lists. I don't understand why, in the following simple code, the string in the position 2 of this list is the same as the string in the position 3:

t = ['a', 'b', 'c', 'd', 'e', 'f']
t[:3]
**['a', 'b', 'c']**
t[0:3]
**['a', 'b', 'c']**
t[1:3]
**['b', 'c']**
t[2:3]
**['c']**

Maybe i'm doing something wrong. But in the third request to Python (t[0:3]) i'm asking Python to print the items in the list starting from the very first one (0) to the fourth one (because Python counts the numbers in a list since 0). Why does it print until 'c'? Shouldn't it print until 'd', considering that 'd' is the item in the position 3 in this list?

The same happens in the last 2 requests: Python recognizes 'c' as the item in the position 3 in this list. I tried to 'force' Python to print the item in the position 2 in the list (by using t[2:3]), and it just ignored 'd' again; whom should be the item in the position 3 in this list.

So, my question is simple: Why does Python recognize 'c' as the item number 3 in the list, when it should be only the number 4? Thanks in advance for reading this post.

  • 1
    When using a slice, the start index is inclusive but the end index is not inclusive. So `[0:3]` means the items at index 0, 1 and 2, which is `['a', 'b', 'c']`. `[2:3]` means just 2, so you get just `['c']`. – shriakhilc Jan 15 '22 at 17:59
  • 2
    Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Robin Dillen Jan 15 '22 at 18:00

1 Answers1

0

First index is always included, end index excluded.