why lista.sort() + listb.sort() doesn't work in python?

Question:

I tried this code in python and it works perfectly:

listX.sort()
list1.sort()

result = listX + list1

but the following code doesn’t work:

result = listX.sort() + list1.sort()

it gives me this error message:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

How can I fix this? Thanks!

Asked By: Ali_IT

||

Answers:

Because the list.sort method operates on the list in place, returning None. In contrast, sorted is a builtin function which does return the sorted output.

result = sorted(listX) + sorted(list1)

That would do what you want.

Answered By: wim

This is because list.sort() returns None, so you are effectively doing:

None + None

which doesn’t even make sense.

If you want to concatenate the sorted elements of two lists, you can either do:

listA.sort()
listB.sort()
listC = listA + listB

or, (recommended):

listC = sorted(listA) + sorted(listB)

as sorted() does return a value.

Answered By: Joel Cornett
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.