Thursday, September 22, 2016

Python: Methods Comparison to Reverse a List Object

There are many ways in Python to reverse items sequence of an iterable object. Uh, anyway, this is on Python 2.7.

For example, we have this list to be reversed:

a = ["A", "B", "C", "D", "R", "Y", 25, 971235]


Methods

  1. reversed_list = list_reference[::-1]
  2. reversed_list = list(reversed(list_reference))
  3. reversed_list = [item for item in reversed(list_reference)]
  4. reversed_list = list(list_reference)
    reversed_list.reverse()
  5. reversed_list = [item for item in list_reference]
    reversed_list.reverse()
  6. And others maybe...

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 -- manual setting), 4 GB DDR2 memory, running on Windows 7 -- 64 bit.

For each runTest execution, my CPU usage went up to around 50% - 70%.


Conclusion

As you can see above, the fastest is using method #1:

reversed_list = list_reference[::-1]

Followed by r_4 (method #4), then r_5 (method #5), then r_3 (method #3).

The slowest is method #2:

reversed_list = list(reversed(list_reference))

We can draw a conclusion that built-in reversed, reverse, and list are "burdening" the process (from the completion time perspective only).

Therefore, to get faster execution, it's recommended to use the generic method (first method) reversed_list = list_reference[::-1] ► it means slice (shallow copy) the list object from list_reference variable, but do it in reverse (from the back) and write it to reversed_list variable.

The list slicing notation syntax (using colon):

new_list = original_list[start:end:step]


JavaScript Equivalency

Like in JavaScript, we don't just put equal operator to copy array (or list in Python).
If like so:

var new_list = original_list;
Then whenever there's an operation that changes the original_list, the new_list is also affected, and vice president. They both are dependent.

In JavaScript, it goes something like:

var new_list = original_list.slice();
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:

new_list.reverse();
We can chain it:
var new_list = original_list.slice().reverse();
This copying - reversing list (method #4 and #5) chain won't work in Python, you'll get None object.


Links


Oh and the reversed list result

The input is:

["A", "B", "C", "D", "R", "Y", 25, 971235]

The output of each method is the same:

[971235, 25, "Y", "R", "D", "C", "B", "A"]

No comments:

Post a Comment

Tell me what you think...