Python .sort() on a list of a set returns None

Question:

Python 3.6

Just had this issue (below), where adding .sort() caused my expression to return None.

Should this work? if not why not?

>>> x = [1,2,3,3,45,5,6,6,7,7]
>>> y = [3,4,34,643,6,234,3,34,5,22,3]
>>> w =[x,y]
>>> x = [set(i) for i in w]
>>> x
[{1, 2, 3, 5, 6, 7, 45}, {34, 3, 4, 643, 6, 5, 234, 22}]
>>> common_elements = list(set.union(*x))
>>> common_elements
[1, 2, 3, 34, 5, 6, 7, 4, 643, 234, 45, 22]
>>> common_elements = list(set.union(*x)).sort() #Adding .sort() returns None
>>> common_elements
>>>                #Nothing, None
Asked By: James Schinner

||

Answers:

sort is inplace. It does the sort and does not return a value.

l = list((4,3,2,1))
l
# OUTPUT
# [4, 3, 2, 1]
l.sort()
l
# OUTPUT
# [1, 2, 3, 4]
Answered By: aquil.abdullah

you have to use the sorted method for sets:

common_elements = list(sorted(set.union(*x)))

sort method is inplace, it wont return anything, the other opcion is

common_elements = list(set.union(*x))
common_elements.sort()
Answered By: Damian Lattenero

Yes, list.sort method sorts the list in place and returns None. If you want to return the sorted list use sorted method.

>>> lst=[5, 2, 1, 4, 3]
>>> lst.sort()
>>> lst
[1, 2, 3, 4, 5]
>>> lst=[5, 2, 1, 4, 3]
>>> lst=sorted(lst)
>>> lst
[1, 2, 3, 4, 5]
>>> 

So you will have to use: common_elements = sorted(list(set.union(*x))) or you can sort in place like this:

common_elements = list(set.union(*x))
common_elements.sort()
Answered By: riteshtch

Don’t reassign common_elements when you call .sort(). .sort() modifies the list in-place and returns None.

Answered By: Paul Back
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.