Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse last N elements of list in python

Tags:

python

list

Suppose I have a list:

>>> numbers = list(range(1, 15))

>>> numbers

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

I need reverse last 10 element only using slice notation

At first, I try just slice w/o reverse

>>> numbers[-10:]

[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Then:

>>> numbers[-10::-1]

I expected [14, 13, 12, 11, 10, 9, 8, 7, 6, 5]

but got [5, 4, 3, 2, 1].

I can solve the problem like this:

numbers[-10:][::-1]

and everything OK

[14, 13, 12, 11, 10, 9, 8, 7, 6, 5]

But I wondering why numbers[-10::-1] doesn't work as expected in my case and if there a way to get the right result by one slice?

like image 664
Eugene Alkhouski Avatar asked Jan 03 '17 14:01

Eugene Alkhouski


People also ask

How do you print the last 3 elements of a list in reverse order Python?

Method 1: Reversing a list using the reversed() and reverse() built-in function. Using the reversed() method and reverse() method, we can reverse the contents of the list object in place i.e., we don't need to create a new list instead we just copy the existing elements to the original list in reverse order.

How do you reverse a few elements in a list Python?

Just use the slice and reverse it.

How do I remove the last n elements from a list?

pop() function. The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.

How do you reverse the order of a list in Python?

Python lists can be reversed in-place with the list. reverse() method. This is a great option to reverse the order of a list (or any mutable sequence) in Python. It modifies the original container in-place which means no additional memory is required.


1 Answers

Is there a way to get the right result by one slice?

Well, you can easily get right result by one slicing with code below:

numbers[:-11:-1]
# [14, 13, 12, 11, 10, 9, 8, 7, 6, 5]

Why numbers[-10::-1] doesn't work as expected?

Well it's work as expected, see enumerating of all slicing possibilities in that answer of Explain Python's slice notation question. See quoting ( from answer i've pointed above) of expected behaviour for your use case below:

seq[low::stride] =>>> # [seq[low], seq[low+stride], ..., seq[-1]]
like image 128
Andriy Ivaneyko Avatar answered Sep 19 '22 18:09

Andriy Ivaneyko