Search code examples
pythonlistmatlabslice

Difference in accessing only last element from a list vs accessing a range up to including the last elements from a list


Being used to work with Matlab syntax now that I'm working with Python this example is confusing:

I have a list for which I want to access its last element, lets say list_a = [0,1,2,3,4,5,6,7,8,9]

In Python I have to do list_a [-1] = 9 when in Matlab I would do list_a(end)

So in my mind -1 in Python means the last element, same as the end keyword in Matlab.

Then I want to access the last 5 elements from the list, including the last one.

In Matlab I would do list_a (6:end). Matlab arrays first index is 1 not 0 like in Python, that's why I have to start with index 6.

In my mind it would be logical to do list_a[5:-1] since -1 means the last item of the list as in the example above. However, this doesn't work in Python, because the returned result is [5, 6, 7, 8] So to get the last element of the list in Python I have to do list_a[5:] and leave a blank

I don't know why they decided to do this but I'm wondering if there is something in Python I can use like the end keyword in Matlab that works for both list indexing and slicing. Thank you


Solution

  • When slicing arrays, for example list[x:y], y is not included. The way python slices arrays is starting from x and ending at y-1.

    Now, when you add the None keyword when slicing a list, python takes it as the end of list. For example, if I did list[1:None], it would grab index 1 to the last index. Confusing, but that's how python works.

    Leaving a blank is the same as None. So, in your example, list_a[5:] is the same as list_a[5:None].

    As for your question, you can technically use None as an END keyword in python.