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?
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With