There are many ways in Python to reverse items sequence of an iterable object. Anyway, this is on Python 2.7x, but it also works on Python 3+.
For example, we have this list to be reversed:
Methods
- And maybe others...
So, we'll test those five methods.
Let's use timeit
module to measure the completion duration for each method for 1,000,000 (one million) trials or loops. Each test will be repeated 5 times.
This was how I typed the test flow:
Results
This is the result on my desktop, ~2 GHz Core Duo Intel (6 × 333 MHz -- manual setting), 4 GB DDR2 memory, running on Windows 7 -- 64 bit.

For each execution, my CPU usage went up to around 50% - 70%.
This is the latest result on Lenovo Legion Ryzen 5 (12 CPUs) -- base clock of 3.3 GHz and a boost clock up to 4.2 GHz, 16 GB DDR4, running on Windows 11 -- 64 bit.
For each execution, my CPU usage went up to around 5% - 7% (one tenth compared to my relic desktop above).
Conclusion
It varies between machines and Python version.
Relic Desktop
As you can see above, on my relic desktop and on Python 2.7x, the fastest is using method #1:
Followed by r_4
(method #4), then r_5
(method #5), then r_3
(method #3).
The slowest is method #2:
Latest Machine
But on my latest machine, Legion, on Python 3.11x, the fastest is still method #1 🤔😅
So actually the ranking goes pretty much the same like the previous machine and Python version. But indeed it is faster because of more CPUs, RAM, and newer architecture in the hardware of this Lenovo Legion machine.
Anyway, the list slicing notation syntax (using colon):
JavaScript Equivalency
Like in JavaScript, we don't just put equal operator to copy array
(or list
in Python).
If like so:
Then whenever there's an operation that changes the original_list
, the new_list
is also affected, and vice versa. They both are dependent.
In JavaScript, it goes something like:
new_list
and original_list
are independent now. We can do operation on either one or both without affecting the other array
unintentionally.
To reverse the (copy of the original) array
, do:
We can chain it:
This copying - reversing list (method #4 and #5) chain won't work in Python, you'll get None
object.
Links
- (Python 2.7) Documentation for timeit library.
- (Python 2.7) Documentation for "deep" and "shallow" copy.
- (Python 2.7) Documentation for Python's data model ➡️ the immutable and mutable sequences definitions and all general definitions/usages.
- Discussion on colon notation for slicing list on Stack Overflow.
- Discussion on fastest method to copy
array
in JavaScript on Stack Overflow.
Reversed Result
The input is:
The output of each method is the same:
Comments
Post a Comment