0

I'm a beginner attempting to learn Python. I am familiarising myself with the list data type; I've defined the following list:

>>> numbers = [1, 2, 3, 4]

Typing:

>>> numbers[0]
1
>>> numbers[1]
2
>>> numbers[2]
3
>>> numbers[3]
4

Given this, why do I get the following when I attempt to retrieve the following list elements:

>>> numbers[0:3]
[1, 2, 3]

Why isn't the list element '4' included in the response from the interpreter?

Thank you for your help.

seeker
  • 530
  • 1
  • 4
  • 14

3 Answers3

2

Slice notation does not include the last element (similar to the range() function in that respect). If you want to include the last element, simply omit an index. Also, the default start is the beginning, so you don't need 0 there either:

>>> numbers[:]
[1, 2, 3, 4]

Note that this is a (shallow) copy of numbers. If you save a reference to it, you can mutate it without affecting the original numbers.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

That's how slicing works in Python. To quote a tutorial:

Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s.

The example uses a string, but slicing works the same way with lists.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

numbers[0:3] list from 0 up to 3 but 3 is excluded (like range(0,3))