list.reverse(): add slice support #19181
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi all,
In Python, I need a tool to reverse part of a list (tail) quickly.
I expected that
would do it inplace with the performance similar to nums.reverse().
However, it doesn't work at all. The fastest way to reverse a part of
the list that I found is like this:
But it is 30 times slower than pure reverse(). The patch below adds
a region support for the reverse(). It works as fast as I expect.
The test script and results are like this:
import time
nums = list(range(10000000))
L = len(nums)
LL = int(L/2)
t = time.time()
nums.reverse()
print('nums.reverse()\t\t\t\t', str(time.time() - t))
t = time.time()
nums = nums[::-1]
print('nums = nums[::-1]\t\t\t', str(time.time() - t))
t = time.time()
nums.reverse(-LL)
print('nums.reverse(-L/2)\t\t\t', time.time() - t)
t = time.time()
nums.reverse(LL, L)
print('nums.reverse(L/2, L)\t\t\t', time.time() - t)
t = time.time()
nums = nums[:LL] + nums[L : LL - 1 : -1]
print('nums = nums[:L/2] + nums[L:L/2-1:-1]\t', time.time() - t)
t = time.time()
nums[LL:L] = nums[L:LL-1:-1]
print('nums[L/2:L] = nums[L:L/2-1:-1]\t\t', time.time() - t)
If there is better way to reverse lists, can someone point me at the right
direction? If not, I'll be happy to fix all existing issues and upstream
this approach.
Thanks,
Yury
Signed-off-by: Yury Norov yury.norov@gmail.com