Python – reversed() VS [::-1] , Which one is faster?

Python lists can be reversed using many Python method such as using slicing method or using reversed() function. This article discusses how both of these work and Which one of them seems to be the faster one and Why.

Code: Reversing a list using Slicing.

Python
# Python code to reverse
# a list using slicing

ls = [110, 220, 330, 
      440, 550]
print('Original list :', ls)

# list reverse
ls = ls[::-1]

print('Reversed list elements :')
for element in ls:
  print(element)

Output:

Original list : [110, 220, 330, 440, 550]
Reversed list elements :
550
440
330
220
110

Explanation : The format[a : b : c] in slicing states that from an inclusive to b exclusive, count in increments of c. In above code, a and b is blank and c is -1. So it iterates the entire list counting from the last element to the first element resulting in a reversed list.

Code: Reversing a list Using reversed() built-in function.

Python
# Python code to reverse 
# a list using reversed()

ls = [110, 220, 330, 440, 550]
print('Original list :', ls)

# list reverse
ls = reversed(ls)
print('Iterator object :', ls)

print('Reversed list elements :')
for element in ls:
  print(element)

Output: 

Original list : [110, 220, 330, 440, 550]
Iterator object : <list_reverseiterator object at 0x7fbd84e0b630>
Reversed list elements :
550
440
330
220
110

Explanation : The built-in reversed() function in Python returns an iterator object rather than an entire list.

Time Complexity : O(n), where n is the size of the given array. 
Auxiliary Space : O(n)

Conclusion :

The time complexity of both A[::-1] and reversed() is O(n)O(n), where nn is the length of the string. This means that they both take the same amount of time to reverse a string, regardless of its length. However, in practice, A[::-1] may be slightly faster than reversed() for large input sizes. This is because reversed() creates an iterator object, which involves some overhead compared to the direct slicing operation of A[::-1].

While both methods have similar time complexity, A[::-1] has a slightly different space complexity. Specifically, A[::-1] creates a new string in memory, leading to an O(n)O(n) space complexity, whereas reversed() creates an iterator which uses O(1)O(1) space initially, but when converted to a list or a string, it also ends up using O(n)O(n) space.


Contact Us