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
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()