why cannot directly use print(something.sort())?

Viewed 497

I am a python beginner, could someone help to explain why this print() doesn't work, and python prints me a None result?

list =['a','c','d','e']
print(list.sort())

so if i make a extra step, i can get the results:

list =['a','c','d','e']
list.sort()
print(list)

Many thanks in advance

4 Answers

list.sort() is a modifying function that modifies the list. It is not a list itself. print(list.sort()) will get you None since there is no list to return from this function.

list.sort() modifies the list in place, meaning that it sorts the list in its current location in memory without returning anything.

What you want is sorted(list), which makes a copy of the list, sorts it, and then returns it.

list.sort() doesn't store your sorted list in a new variable, instead, it modifies the list directly, think of it as a procedure. you can still keep your original list by making a copy of it, just use the build-it copy method

Code:

list =['c','a','d','e']

# saving a copy of our original list
originList = list.copy()
print("original list:",originList)

# sorting our list
list.sort()
print("sorted list:",list)

Output:

oiginal list: ['c', 'a', 'd', 'e']  # the copy (now it's the original)
sorted list: ['a', 'c', 'd', 'e']    # the original (now it's sorted)

Answering the question implied by what you're trying to do:

If you want a one-liner to print the sorted list, you can use

print(sorted(the_list))

Note that sorted(the_list) returns a new, sorted version of the_list, and the_list remains unmodified afterwards.

Related