0

I've been trying to sort a list of names alphabetically, let's say:

list=['Bob','Alice','Charlie']
print(list.index('Alice'))
1

However I'd also like to keep track of the original indexes, so this won't work:

list.sort()
print(list)
['Alice','Bob','Charlie']
print(list.index('Alice'))
0

After sorting the indexes changed; is there any way of keeping track of the original indexes? I've checked other similar questions and numpy has a solution, but not useful for str variables.

5
  • 1
    You can create a copy of the original list and use it for referring to original indexes. Commented Apr 30, 2020 at 4:35
  • is your list unique ? Commented Apr 30, 2020 at 4:35
  • Kinda depends on why you want that and what you plan to do with that information. Commented Apr 30, 2020 at 4:48
  • How can I do that? I tried to make a copy, say templist=list, but modifying elements in list also changes the ones in templist. Commented May 1, 2020 at 16:17
  • ON 'why', I'm trying to make a list of members, each one with a unique ID number... And I'd like that number to be associated with the list index Commented May 1, 2020 at 16:19

6 Answers 6

5

Just sort the reversed (index, name) tuples from enumerate to keep track of the elements and their indices:

>>> names = ['Bob','Alice','Charlie']
>>> sorted((name, index) for index, name in enumerate(names))
[('Alice', 1), ('Bob', 0), ('Charlie', 2)]
Sign up to request clarification or add additional context in comments.

Comments

4
l = ['Bob','Alice','Charlie']
e = enumerate(l) # creates a generator of [(0, 'Bob'), (1, 'Alice'), (2, 'Charlie')]
sl = sorted(e, key=lambda x: x[1]) # [(1, 'Alice'), (0, 'Bob'), (2, 'Charlie')]

Comments

3

You may create another list of indices and sort that one, leaving the original untouched:

>>> a = ['Bob', 'Alice', 'Charlie']
>>> idx = range(len(a))
>>> idx
[0, 1, 2]
>>> sorted( idx, key=lambda x : a[x] )
[1, 0, 2]
>>> 

2 Comments

range() returns a list?
@PalakKumarJha yes, unless you use python 3 or something
1

You could create a nested dictionary of sorts to hold the original index and sorted value.

First I would recommend to use a proper name for your list object, list is a keyword in python.

names=['Bob','Alice','Charlie']

name_dict = {name : {'unsorted' : idx} for idx,name in enumerate(names)}

for sorted_idx, name in enumerate(sorted(names)):
    name_dict[name].update({'sorted' : sorted_idx})

print(name_dict['Bob']['sorted'])
1
print(name_dict['Bob']['unsorted'])
0

print(name_dict)

{'Bob': {'unsorted': 0, 'sorted': 1},
 'Alice': {'unsorted': 1, 'sorted': 0},
 'Charlie': {'unsorted': 2, 'sorted': 2}}

2 Comments

I think this is a good demonstration of what happens before and after sorting.
Thanks, now that i think about it, your answer is much more succint @RoadRunner cool to see another Microsoft Azure nut around :)
0

Sort a list alphabetically and retrieve initial index elemnt in python

l=['Bob','Alice','Charlie']
def sort_and_get_first_element(list1):
    list1.sort()
    return list1[0]
print sort_and_get_first_element(l)

1 Comment

I am not going to downvote because this, but this does not answer the question asked at all. You are just returning the first item from the sorted list.
0

Yes, you can keep track of initial index but with different data structure

a = ['Bob','Alice','Charlie']
l = sorted(enumerate(a), key=lambda i: i[1])
print(l)

Now the sorted list that keep track of initial index is,

[(1, 'Alice'), (0, 'Bob'), (2, 'Charlie')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.