Python reverse() vs [::-1] slice performance

Question:

Python provides two ways to reverse a list:

List slicing notation

['a','b','c'][::-1] # ['c','b','a']

Built-in reversed() function

reversed(['a','b','c']) # ['c','b','a']

Are there any relevant differences in implementation/performance, or scenarios when one is preferred over the other?

Asked By: Michael Moreno

||

Answers:

The slicing operator constructs a new list in memory, which has implications on both memory and runtime.

reversed, on the other hand, returns an iterator which simply yields items one after another from the original list in reversed order. It does not allocate any additional memory.

So if all you’re doing is iterating over the list in reverse and there’s no need to construct a new (for example if you need to mutate it), then I’d say go for reversed.

Answered By: Tomer Ariel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.