Janghoo Lee
Janghoo Lee

Reputation: 13

Why python sort function for string list does not work

print(['at', 'from', 'hello', 'hi', 'there', 'this'].sort())

returns

None

1: https://thispointer.com/python-how-to-sort-a-list-of-strings-list-sort-tutorial-examples/
2: How to sort a list of strings?

I saw two examples, but why not work?

Upvotes: 1

Views: 902

Answers (2)

Guy
Guy

Reputation: 50864

sort() doesn't have return value, so it return default None. It modifies the original list, so you need to use it on a list name

l = ['at', 'from', 'hello', 'hi', 'there', 'this']
l.sort()
print(l)

If you don't want do modify the list you can create sorted copy with sorted()

l = ['at', 'from', 'this', 'there', 'hello', 'hi']
print(sorted(l)) # prints sorted list ['at', 'from', 'hello', 'hi', 'there', 'this']
print(l) # prints the original ['at', 'from', 'this', 'there', 'hello', 'hi']

Upvotes: 3

Daniel Domingos
Daniel Domingos

Reputation: 63

I think this has to do with the function sort() and where it works. sort() will only act upon a mutable data type, which must be a list or something like it. It has no return, it only modifies a data type. This is why it will return a sorted list, as the list has passed through the sort() function. When you run this program:

>>> i = ['at', 'from', 'hello', 'hi', 'there', 'this']
>>> i.sort()
>>> print(i)
['at', 'from', 'hello', 'hi', 'there', 'this']
>>> 

It works fine, as the sort() function is being called to a variable.

Upvotes: 0

Related Questions