Today we will compare the performance difference between different ways of reversing a list.
We are using the reversed built-in function, reverse method for a list, and reverse using slicing.
Let us learn this with an example
import timeit def using_reversed(): a = list(range(500)) return reversed(a) def using_slicing(): a = list(range(500)) return a[::-1] def using_reverse(): a = list(range(500)) return a.reverse() time_for_reversed = timeit.timeit(using_reversed, number=1000_000) time_for_reverse = timeit.timeit(using_reverse, number=1000_000) time_for_slicing = timeit.timeit(using_slicing, number=1000_000) print("Time taken for using_reversed: ", time_for_reversed) print("Time taken for using_reverse: ", time_for_reverse) print("Time taken for using_slicing: ", time_for_slicing)
Time taken for using_reversed: 4.080789330997504 Time taken for using_reverse: 4.0947380370053 Time taken for using_slicing: 5.765078948003065
If we check reversed and reverse this time are almost close. But the difference between them is reversed returns an iterator object. But the reversed function does in-place reordering. If slicing a new list is created and also slow compared to other methods.
If your list is huge and there is no issue with modifying the order of the original list use the reverse method. Which is more memory efficient. If your order of the original is maintained and also faster performance then use reversed function
Hope you have learned something from this post. Please share your valuable suggestions with firstname.lastname@example.org