1
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?

  • 1
    Possible duplicate of [Python Sort() method](https://stackoverflow.com/questions/9408050/python-sort-method) – abhilb Nov 13 '19 at 06:19

2 Answers2

3

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']
Guy
  • 46,488
  • 10
  • 44
  • 88
0

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.