M.Jones
M.Jones

Reputation: 469

Difference between reverse and [::-1]

Just wanted to know the difference between reverse() and [::-1] in terms of references.

For example

p = [1,2,3] 
x = p[::-1] 
print(x) 
print(p) 

p.reverse() 
print(p ==p[::-1]) 
print(p == x) 

so outputs are

[3,2,1]
[1,2,3] 
False
True 

Upvotes: 21

Views: 14485

Answers (2)

Allan
Allan

Reputation: 12446

Regarding reversing list in python, the 3 main ways:

  • the built-in function reversed(seq) that will return a reverse iterator which is an object representing the stream of data that will return successive items of this steam. Generating this reverse iterator is O(1) in time/space complexity and using it to iterate through the elements of a list will be O(N), O(1) in time/space complexity where N is the length of the list. This is the approach you want to go for if you simply want to iterate on the reversed list without modifying it. This approach gives the best performances in this case.

  • p.reverse() reverses the list in-place. The operation is O(N), O(1) in time/space complexity as it will have to go through half of the elements of the list to reverse them and it doesn't store the results in a new list. p.reverse() will return None and the elements will be directly reversed in p after this instruction. This approach is good if you do NOT need to keep the original list and you have several passes/operations to do on the elements of the reversed list and if you have to save the processed reversed list.

  • Using slicing [::-1] creates a new object of the list/a copy in reversed order. The operation is O(N), O(N) in space/time complexity as you have to copy all the elements of the list in the new one and this new list will also consume the same amount of space as the original list. In terms of reference, you will have a new object created so even if print(p == x) returns True, print(p is x) will return False as the two objects even if they share the same values have different references. This approach is great if you need to keep the original list and have a reversed copy of it stored in a different object for further processing.

To summarize, depending on your use case you will have to use one of those 3 approaches that have slightly different objectives and completely different performances.

Upvotes: 7

Yu Hao
Yu Hao

Reputation: 122483

reverse reverses the list in-place, see the manual, while [::-1] gives a new list in reversed order.

Try print(p) after calling p.reverse(), you'll see the difference.

Upvotes: 25

Related Questions