I had a bug with the following code and figured out the reason:
myset = set(["A", "C", "B"])
# Original Code: Fails output: None
print(list(myset).sort())
list.sort() is an inplace sort with no return value, and this is passing the return from the sort() call to print; which is why this code doesn't work.
To fix it, I can obviously use the sorted function or write my own:
# Method 1: Works out: ['A', 'B', 'C']
print(sorted(myset))
# Method 2: Works out: ['A', 'B', 'C']
def mysetsort(s):
l = list(s)
l.sort()
return l
print(mysetsort(s))
is there any way to do this along the lines of the original buggy inline implementation? ie use sort() on the temporary list from the cast, but pass in/return the temporary (sorted) object?
I'm kind of expecting the answer no, but I'm still learning python.
Thx