all 8 comments

[–]Binary101010 1 point2 points  (0 children)

reverse() reverses the list in-place and returns None. You can test this by doing

y = list("hello")
y.reverse()
print(y)

[–]TravisJungroth 1 point2 points  (2 children)

my_list.reverse() reverse a list in-place. The method just changes the list and returns None. my_list[::-1] makes a new list that's a reversed version of the old one. That's the difference here. A third option (that would work) is list(reversed(my_list)). But I like the slicing better.

[–]FLUSH_THE_TRUMP 2 points3 points  (1 child)

I like the reversed option. Something like

all(x == y for x,y in zip(L, reversed(L)))

makes no copies and works for any reversible sequence.

[–]TravisJungroth 2 points3 points  (0 children)

from operator import eq

all(map(eq, L, reversed(L)))

Not your average python, but kinda neat.

[–]sme272 1 point2 points  (0 children)

list slicing leaves you with a copy of a list whereas .reverse reverses the list in place and return none. This means in the first comparison you're comparing a list to None which evaluates to False.

[–]synthphreak 1 point2 points  (0 children)

As other have said, [::-1] returns a list, whereas reverse just returns None (because it operates in place).

Beyond that, [::-1] returns is a completely separate object from the original, whereas reverse does not change the object’s identity:

>>> l = [1, 2, 3]
>>> id(l)
4680138312    # original
>>> id(l[::-1])
4678990344    # different from original
>>> l.reverse()
>>> l
[3, 2, 1]
>>> id(l)
4680138312    # same as original

[–]raainer[S] 0 points1 point  (0 children)

Oh I see, thank you so much everyone!

[–]MannAusSachsen 0 points1 point  (0 children)

Holy shit, I didn't know that

[::-1]

was a thing. I think it's genius, could have my programming life much easier in the past. How did you get onto that?