Skip to main content

Posts

Showing posts from September, 2016

Python: Methods Comparison to Reverse a List Object

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: a = ["A", "B", "C", "D", "R", "Y", 25, 971235] Methods reversed_list = list_reference[::-1] reversed_list = list(reversed(list_reference)) reversed_list = [item for item in reversed(list_reference)] reversed_list = list(list_reference) reversed_list.reverse() reversed_list = [item for item in list_reference] reversed_list.reverse() 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: """ Module for stopwatch """ import timeit test_list = ["A", "...