0

Does anyone know a good way to retrieve back the indexes of elements in the unsorted list after sorting that list in python?
Let's say for example I want to find the largest element in a list, so I sort it and find the last element(as it will be the largest), now I want to retrieve its original position in the unsorted list.

Comments
  • 1
    Dictionary, just create one with the elements and they're indexes
  • 5
    Make a second list and sort that so you can retain the original, or what @p100sch said.
  • 1
    @tits-r-us
    nums = [4,3,5]
    nums1 = sorted(nums)
    #nums1 = [3,4,5]
    maxElement = nums1[len(nums1)-1]
    for i in range(len(nums)):
    if nums[i] == maxElement
    oldIndex = i
  • 0
    But the above logic fails when there are duplicate elements as this logic will give the last found element from the list.
    eg list = [1,3,2,3]
  • 1
    What are you trying to do that you need to remember the indices?
  • 0
    Sounds like homework for a CS course. If it is, it's intended to get you thinking in the frame of mind of these objects and structures. A huge amount of the value of a good programmer is the ability to come up with creative solutions to unexpected problems. Asking for, "the answer" on an online forum ignores that.
  • 1
    @korrat
    https://leetcode.com/problems/...
    I was trying to solve the above problem which requires that.
    So my approach requires sorting the list first but that leads to change in indexes of list elements, which creates a problem.
  • 1
    @ishank-dev in that case you could map the numbers to pairs of index and number and then sort by number.
  • 0
    @korrat Thanks thats a great idea..
Add Comment