Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of reversed() in Python 3

What is the time complexity of reversed() in Python 3?

I think the answer would be O(1) but I want to clarify whether it is right or wrong.

like image 656
somesh Avatar asked Sep 05 '25 15:09

somesh


1 Answers

reversed(some_list) always takes about 120ns to finish on my machine, which is a clear sign of O(1) time complexity. This is because this function does not actually change any values, it just returns a list_reverseiterator, which iterates the list backwards. This object is very similar to a normal generator, as it its elements get consumed, when you are, for example, calling list on it:

In [10]: a = [i for i in range(5)]

In [11]: b = reversed(a)

In [12]: b
Out[12]: <list_reverseiterator at 0x7f11fe3615b0>

In [13]: list(b)
Out[13]: [4, 3, 2, 1, 0]

In [14]: b
Out[14]: <list_reverseiterator at 0x7f11fe3615b0>

In [15]: list(b)
Out[15]: []
like image 56
user8408080 Avatar answered Sep 08 '25 11:09

user8408080