Anders Arvidsson
Anders Arvidsson

Reputation: 23

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!

Upvotes: 2

Views: 137

Answers (2)

Moberg
Moberg

Reputation: 5501

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

Try for m in sorted(movies): instead.

Upvotes: 5

Simeon Aleksov
Simeon Aleksov

Reputation: 1333

Just make a copy of your list, because movies.sort(), modifies to original list.

copyMovies = movies[:]

Here's an example:

>>> movies = ["Star Wars", "Hamilton", "Fight club", "Beck", "Wallander"]
>>> copyMovies = movies[:]
>>> movies.sort()
>>> movies
['Beck', 'Fight club', 'Hamilton', 'Star Wars', 'Wallander']
>>> copyMovies
['Star Wars', 'Hamilton', 'Fight club', 'Beck', 'Wallander']
>>>

Upvotes: 1

Related Questions