Search code examples
pythonlistenumerate

Sort an enumerated list by the value


MWE:

list1 = [2,5,46,23,9,78]
list1 = list(enumerate(list1))

Now suppose I want to sort this list by the index 1, i.e. by the original list1, in say, ascending order. How do I do that?

I would like something that could then give me both the indexes and the values.

list2 = sorted(list1[1], key=float)

Solution

  • Sort with item[1] as key:

    >>> list2 = sorted(list1, key=lambda x:x[1])
    >>> list2
    [(0, 2), (1, 5), (4, 9), (3, 23), (2, 46), (5, 78)]