Why does list.sort return none when you make it a variable?

Question:

Hello guys so I am learning a bit of python and currently I am trying to sort lists.

my python code

def len_sorting(var1, var2):
    if len(var1) == len(var2):
            return 0
    elif len(var1) > len(var2):
            return 1
    else:
            return -1 

list.sort(cmp=len_sorting)
print list.sort(cmp=len_sorting)

This works fine but when I trie to place the list.sort in a variable and print it it returns None

code

sorted_list = list.sort(cmp=len_sorting)
print sorted
reverse_sorted = list.sort(cmp=len_sorting, reverse=True)
print reverse_sorted

both will return None

Thanks in Advance!

Asked By: user3261212

||

Answers:

Because it modifies the list in-place so it doesn’t return anything. In the other hand you can use sorted() which will return the modified list.

Answered By: Christian Tapia
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.