Montel Edwards
Montel Edwards

Reputation: 400

Why does .sort() actually change the variable?

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

Answers (2)

Batman
Batman

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

Anonymous
Anonymous

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

Related Questions