Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a list slice in python

I am trying to reverse slice of a list in python but it returns an empty list. But when I try with whole list, it works fine. Am I missing anything here?

l = [1,2,3,4,5,6,7,8]
l[::-1] = [8, 7, 6, 5, 4, 3, 2, 1]     # <<< This worked fine.

l[2:5] = [3, 4, 5]
l[2:5:-1] = []       # <<< Expecting [5,4,3] here.

Any clues?

like image 342
vdani Avatar asked Dec 04 '15 10:12

vdani


People also ask

How do you reverse slice?

Method #1 : Using join() + reversed() The combination of above function can be used to perform this particular task. In this, we reverse the string in memory and join the sliced no. of characters so as to return the string sliced from rear end.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

How do you reverse a list without reverse function and slicing in Python?

Another way to reverse the python list without the use of any built-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed.


1 Answers

The syntax is always [start:end:step] so if you go backwards your start needs to be greater than the end. Also remember that it includes start and excludes end, so you need to subtract 1 after you swap start and end.

l[5:2:-1]= [6, 5, 4]
l[4:1:-1]= [5, 4, 3]
like image 146
Sorin Avatar answered Sep 18 '22 00:09

Sorin