0
x=[1,2,3,4]

In [91]: x[:1]
Out[91]: [1]

x[:n] select up to 'n' (exclusive) columns?

In [93]: x[:-1]
Out[93]: [1, 2, 3]

How does x[:-1] work?

In [94]: x[::-1]
Out[94]: [4, 3, 2, 1]

And what about x[::-1]? There are two :: here.

Matthieu Moy
  • 15,151
  • 5
  • 38
  • 65
user697911
  • 10,043
  • 25
  • 95
  • 169

3 Answers3

1
  • x[:1] gets the all the values that index is smaller than 1 (so basically just get zeroth element)

  • x[:-1] gets all values until last value

  • x[::-1] reverses the list

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

You can imagine Python slice x[start:end] as an interval [start, end). Besides, missed sign can be 0 or len(x).

x = [1, 2, 3, 4]

  • x[:1] is x[0:1] and it's [0]
  • x[:-1] is x[0:len(x)-1] and it's [1, 2, 3]
  • x[::-1] is a reversed x and it's [4, 3, 2, 1]
avdotion
  • 105
  • 8
1

x[start:stop:step] is the basic format
If any of the three are not specified, they take the default values, start = 0, stop = just after last element, step = 1
According to string indexing, x[1] is the second index and x[-1] is the last index.

  1. So, x[:1] => x[0:1:1] which means all from 0 to 1 not including 1 with an interval of 1.
  2. Similarly, x[:-1] => x[0:-1:1] which is basically x from 0 (begin) up to -1 (end) not including -1 with a step of 1
  3. Lastly, x[::-1] goes through the whole string from start to end but it uses a step of -1 so it works a little special and gives you x[-1: before begin: -1] i.e. from the end to the begin not including the one before the start (no index for that one)
DarkElf73
  • 53
  • 9
  • Why isn't x[-0] the last index? because x[0] is the firs index. – user697911 Sep 23 '18 at 17:01
  • Because x[-0] would still be x[0] which has a different meaning. Reverse indexing starts at -1 and ends at -length while normal indexing goes from 0 to length-1 – DarkElf73 Sep 23 '18 at 17:44