Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 920
M.Jones Avatar asked Jun 05 '16 02:06

M.Jones


1 Answers

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.

like image 199
Yu Hao Avatar answered Sep 20 '22 20:09

Yu Hao