Aly Abdelaziz Aly Abdelaziz - 1 year ago 54
Python Question

Sort nested tuple in Asceding Order

I have a nested tuple similar to:

cluster = [(0,0), (0,2), (0,1), (2,1), (1,2), (2,0), (1,0), (0,1)]

I am trying to sort the values in ascending order. Not by first element or second, but ascending order. The result should be:

sorted_cluster = [(0, 0), (0, 2), (0, 1), (1, 2), (1, 2), (0, 2), (0, 1), (0, 1)]

Looking online, solutions are usually to either sort by the first or second element, but in this case i wish to sort in ascending order. I was able to do:

for i in range(len(cluster)):

However, in doing so, i am returning a nested list inside a nested list which is not what i am looking for. As when i use
it recognizes an "unhashable list".

Answer Source

sorted always returns a list, so just convert it into a tuple. And don't loop over the indices of cluster if you are just going to use the indices to access the elements inside a list, iterate over the elements themselves the Pythonic way:

for c in cluster:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download