0

I've seen a few questions about copying parts from Arrays or list, but I still don't understand the logic behind it... It makes no sense for me that I can get each values by calling them by index, but it is not possible to get a part of the list by calling it by index, too...

x=[0,1,2,3,4,5]
>>>x[2]
2
>>>x[4]
4
>>>x[2:4]
[2,3]

What I am expecting in the last line would be that the command returns the value with index two,three and four !

>>> x[2:4]
[2,3,4]

Is there a command that does it the way I thought it would be?

DavidG
  • 24,279
  • 14
  • 89
  • 82
HKC72
  • 502
  • 1
  • 8
  • 22
  • 2
    You need to read on how the slice operator works. What you are trying to do is subscript the list. Start by reading [this](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) post. – pstatix Oct 24 '17 at 14:14
  • https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation here, this might help you – voiDnyx Oct 24 '17 at 14:14
  • How about `x[2:4+1]` ? – jadsq Oct 24 '17 at 14:16
  • @DavidG Yea I linked that. OP can also read the [docs](https://docs.python.org/3/tutorial/introduction.html#lists). – pstatix Oct 24 '17 at 14:20
  • @jadsq The more appropriate logic is `x[start:until]`, or `x[start:end-1]`, where the RHS of the slice operator is not inclusive. – pstatix Oct 24 '17 at 14:21

3 Answers3

2

You are missing that x[2:4] gets all values where the index is 2 <= index < 4. Therefore, you get index 2 and 3, but not 4. This is done so that you can always tell the size of a partial list (not just in python but in computing in general) by subtracting the upper bound by the lower bound. 4 - 2 = 2, therefore the list has two items in it.

There is an interesting piece of writing by E.W. Dijkstra about this if you care to read it here.

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Alex Eggers
  • 328
  • 3
  • 16
0

The operation that you are performing :

x[2:4]

is called the slicing operation. The format of it such that, for a list[x:y] you get the values in index from the range x to y-1. ie, list[x]...list[y-1]

Hence, when you do x[2:4] , you will get the values from

x[2]...x[4-1] => x[2]...x[3]

Hence you have for :

>>> x = [0,1,2,3,4,5]
>>> x[2:4]
=> [2, 3]

#should be
>>> x[2:5]
=> [2, 3, 4]

A few reading references :

Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
0

You can do

x[2:5]

Because writing x[a:b]starts from index a up to and not including index b So in your case you needed x[a:b+1]

Will Deary
  • 21
  • 3