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!
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.
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!
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.