Open In App

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

Last Updated : 19 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Reversing a list using Slicing

The format [a : b : c] in slicing states that from an inclusive to b exclusive, count in increments of c. In the above code, a and b are 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.

Python
# Python code to reverse a list using slicing

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

# Reversing the list using slicing
reversed_list = original_list[::-1]

# Printing the reversed list elements
print('Reversed list elements:')
for element in reversed_list:
    print(element)

Output:

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

Reversing a list Using reversed() built-in function

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

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

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

Conclusion

Both slicing (A[::-1]) and the reversed() method provide a time complexity of O(n), where n is the length of the string. This means they 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 can be marginally slower than directly accessing the characters in the string. Additionally, A[::-1] has a slightly lower space complexity, making it a more efficient choice for reversing strings with large input sizes.

Moreover, the A[::-1] function is easier to read and understand, which can be beneficial in many applications. Ultimately, the best choice of function will depend on the specific needs of the application, but A[::-1] is generally a faster and more straightforward option for reversing strings, especially with large inputs.


Next Article
Article Tags :
Practice Tags :

Similar Reads