Why is the syntax for selecting the last x elements of a list [-x:] instead of [:-x]?

Another related question for the same list slicing mission (link below);

"When we need to select the first or last x elements ( x stands for a number), we can use even simpler syntax shortcuts:

  • a_list[:x] when we want to select the first x elements.
  • a_list[-x:] when we want to select the last x elements."

Why does the colon : have to move - it goes from :x to -x:
Why not just type the colon : first for both instances -whether I want to select the first or last ‘x’ elements? I find some of these syntax rules to be arbitrary…and not totally efficient…

List slicing mission link:
https://app.dataquest.io/m/312/lists-and-for-loops/5/list-slicing

1 Like

Because that’s how the syntax was designed to work.

When you run a_list[0:x], you select the first x elements, and a_list[:x] is just the short for it. Using the same logic, a_list[-x:] is just the short for a_list[-x:-1], which helps the user to intuit that the selection is happening backwards. That is how I see it.

I understand if you think it is arbitrary or not efficient, but that’s how python is.

1 Like

Adding to @otavios.s’s answer.

It’s easier to remember negative indexing as len(list) - i, where i is the negative index you use.

So, for a list

a = [0, 1, 2, 3, 4, 5]

len(a) is 6.

If I want a[-4], that means I want a[len(a) - 4], which is a[6 - 4] = a[2], and that gives us 2.

If I want to slice values from a, then the same concept applies.

If I say a[-4:], it means I want

a[len(a) - 4:] = a[6 - 4:] = a[2:]

And that’s just normal slicing then.

Now, let’s say you have a list of 1000 elements. And for whatever reason, you wanted to use the last 10 elements for something.

You could either do -

a[990:]

or you could do

a[-10:]

If you don’t know the actual length of the list, then you would do -

a[len(a) - 10:]

Which is pretty much the same as a[-10:]

In this particular case, I would say that this isn’t really arbitrary.

Every programming language will have some rules like these which potentially make the language easier to work with. There also are often more complex/convoluted ways to do some things, in Python or otherwise, and we just have to get comfortable understanding and working with those over time.

1 Like