Anders Arvidsson Anders Arvidsson - 18 days ago 5
Python Question

Python, sorting my list from its original form

I have been searching but haven't found any thread that matches what I'm looking for. What I'm trying to do, is sorting a list from 3 different options, Chronological(The original list), Alphabetical and Reversed sorting.
All of them, I have figured out, for example here is my list:

movies = ["Star Wars", "Hamilton", "Fight club", "Beck", "Wallander"]


And here's my code:

def print_movies():
global movies
j = 0
while j < 1:
print("Hur vill du skriva ut filmerna?")
print("1. Kronologisk\n2. Alfabetisk stigande\n3. Alfabetisk fallande")
choice = input()
if int(choice) == 1:
print("Filmer i samlingen just nu:\n")
for i in movies:
print(i)
j = j+1
elif int(choice) == 2:
print("Filmer i samlingen just nu:\n")
movies.sort()
for i in movies:
print(i)
j = j+1
elif int(choice) == 3:
print("Filmer i samlingen just nu:\n")
movies.sort(reverse=True)
for p in movies:
print(p)
j = j+1
else:
print("Not a valid option, try again")


The sorting and everything works fine, but when I for example press: 2, sort in Alphabetical, it prints out Alphabetical, and when I press: 1 the next time, it doesn't go back to Chronological.
So the option 2 and 3 works fine, it can sort from highest Alphabetical character to reversed sorting but it wont go back to its original list form, and by that I mean:

["Star Wars", "Hamilton", "Fight club", "Beck", "Wallander"]


When I press: 1, its still sorted in either option 2 or 3 of which I entered before.

Would really appreciate the help here.
Thanks!

Answer

a_list.sort() modifies the list. so you will lose your original ordering.

Try for m in sorted(a_list): instead.

Comments