Tan Tan - 1 year ago 105
Python Question

"None" string appear after print a line in python

I a new in python programming. Today I practice with sorting a list.
I've got a strange output with this code:

# problem 13
def lensort(list):
list.sort(key=lambda x: len(x))
print list

print "Sort by length: ", lensort(['python', 'perl', 'java', 'c', 'haskell','ruby'])

The output is:

Sort by length: ['c', 'perl', 'java', 'ruby', 'python', 'haskell']

So, I have no idea the reason why "None" is shown in 2nd line.
Could anyone help to about this problem?

Thank you very much!

Answer Source

Because you are printing the list at the end of lensort function instead of returning it. A function in Python implicitly returns None if it doesn't return anything explicitly.

def lensort(list):
    list.sort(key=lambda x: len(x))
    return list 

By the way, you can simplify the key function passed as follows: list.sort(key=len)

Also, avoid using class names as a variable name such as list, set, dict or object:

def lensort(lst):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download