account
account

Reputation: 15

Why isn't lst.sort().reverse() valid?

Per title. I do not understand why it is not valid. I understand that they mutate the object, but if you call the sort method, after it's done then you'd call the reverse method so it should be fine. Why is it then that I need to type lst.sort() then on the line below, lst.reverse()?

Edit: Well, when it's pointed out like that, it's a bit embarrassing how I didn't get it before. I literally recognize that it mutated the object and thus returns a None, but I suppose it didn't register that also meant that you can't reverse a None-type object.

Upvotes: 0

Views: 406

Answers (3)

Ajay Lingayat
Ajay Lingayat

Reputation: 1673

You can also try reversing the list while sorting Like

lst.sort( reverse=True )

Upvotes: 0

Unsigned_Arduino
Unsigned_Arduino

Reputation: 366

Put simply, lst.sort() does not return the list sorted. It modifies itself.

>>> lst = [3,1,2,0]
>>> lst
[3, 1, 2, 0]
>>> lst.sort().reverse()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'reverse'
>>>

Since lst.sort() doesn't return anything, Python automatically returns None for you. Since None doesn't have a reverse method, you get an error.

>>> lst.sort()
>>> lst.reverse()
>>> lst
[3, 2, 1, 0]
>>>

Upvotes: 1

Fedya Grab
Fedya Grab

Reputation: 46

When you call lst.sort(), it does not return anything, it changes the list itself. So the result of lst.sort() is None, thus you try to reverse None which is impossible.

Upvotes: 1

Related Questions