Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reversing list using slicing [ : 0:-1] in Python

Tags:

python

I am confused in the list slicing in Python.

For a list

L=[0,1,2,3,4,5,6,7,8,9,10]

I wanted to reverse the list and could get the answer by

L[::-1] 

getting [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0].

However, when I tried

L[10:0:-1]

I got [10,9,8,7,6,5,4,3,2,1] without 0. Neither L[10:1:-1] nor L[10:-1:-1] give the answer.

On the other hand, L[200::-1], L[10:-12:-1] gives correct answer, though L[200], L[-12] is out of bounds.

I would like to understand the underlying logic of Python for this case. Thank you.

like image 750
user2775514 Avatar asked Dec 25 '22 20:12

user2775514


1 Answers

Let's take a list for example,

a = [1, 2, 3, 4, 4, 5, 6, 9]

If you try to slice it using positive indices,

newa = a[1:5] 

This will result in

newa = [2, 3, 4, 4] 

This is because, in the above case slicing occurs like this, a[inclusive : exclusive], first index is included and slicing begins from this index, and end just one index before the index(5), exclusive(remember). This is just the way how list slicing works.

To get last two values of the list a,

newa = [6 : ]

Here, the index starts from 6(inclusive) and ends till end of the list.

If you are keen in using negative indexing in lists as Python offers to ease up indexing, know once and for all the inclusive and exclusive thing about slicing.

For same example above, to get last two numbers of the list using negative index, what we do is,

newa = a[-2 : ]

In the case of positive indexing, the index begins at 0 while for negative indexing, the index is at -1, -2 and so on. So in the above example, starting from second last number in the list, slice till the end of the list, is what is understood.

Now, to reverse the list, one could do,

print a.reverse()
[9, 6, 5, 4, 4, 3, 2, 1]

In slicing way, list can be reversed by giving it a [start, end, step] like mentioned above, but I would like to clarify it further.

 r = a[2: : -1]

This will make a new list starting with number from index 2, and till the end of the list, but since the step is -1, we decrease from index 2, till we reach 0. Hence we come up with a reversed list of first three numbers as below:

r = [3, 2, 1]

Also, to get a whole of the list as reversed,

r = a[len(a): : -1]

This will start from 8, the length of the list, but in indices terms which begins from 0, we have 0 till 8 indices, so starting from 8th indices, it goes on decreasing in steps of -1, till the end of the list. The result is as:

[9, 6, 5, 4, 4, 3, 2, 1]

I personally prefer to use this for reversing the list.

like image 188
hlkstuv_23900 Avatar answered Feb 15 '23 06:02

hlkstuv_23900