I want to unsort a list. For you to understand:
list1 = ["Hi", "Whats up this Morning" "Hello", "Good Morning"]
new_list = sorted(list1, key=len, reverse=True)
["Whats up this Morning", "Good Morning", "Hello", "Hi"]
And know it should go back exactly in the same way it was in the beginning
["Hi", "Whats up this Morning", "Hello", "Good Morning"]
Anyone knows the answer?
Getting to it right out of the gate,
list1never changes, so as long as you retain this object in memory you will always have a way to refer to the original list, since it's unchanged.new_listis a new object, and the absolute simplest thing you can do is keep both these objects and refer to them at will.Taking your question from a conceptual standpoint: is there a way to keep track of the original order based on the new object? If you absolutely needed to revert to the original order based only on the
new_list, you could first index the list usingenumerate(). This tracks the order of your object like so:(0, 'Hi') (1, 'Whats up this Morning') (2, 'Hello') (3, 'Good Morning'). Then, you can sort by the length of the second object in each tuple (the original string) withnew_list = sorted(enumerate(list1), key=lambda x: len(x[1]), reverse=True). Finally, you can extract your original list (as a tuple) withwords, indices = zip(*new_list). Then reversing back to the string is quite simple, see the below example: