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

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.