Reputation: 400
I am learning Python and I came across the sort method and I want to understand why running sort.() actually changes the list and I don't have to reassign it?
>>> list = [88,1,4,56,9,7,8,9]
>>> list
[88, 1, 4, 56, 9, 7, 8, 9]
>>> list.sort()
>>> list
[1, 4, 7, 8, 9, 9, 56, 88]
Upvotes: 0
Views: 560
Reputation: 8927
Basically, because it can.
Lists are mutable objects, so the sort()
method can modify it. There's already a sorted()
function, so it doesn't make much sense to have it leave the object unmodified.
Strings are immutable, so they cannot be modified in place. The upper()
method cannot modify the original string.
Upvotes: 0
Reputation: 11
.sort() is a method of the list class. which means when it is called is directly changes the list stored inside of the class.
Upvotes: 1