Search code examples
pythonpython-3.xlistuser-input

How to sort list from latest user input to last


Hey guys I want the list that the user is creating with input to print in the order from latest entry to first entry..

the code I have right now does it for a few posts then it prints the list in some weird order

all_status_updates = []


def status():
    while True: 
        status = input("Type Status Update Here...\n")
        if status != "exit":
            all_status_updates.append(status)
            all_status_updates.sort(reverse = True) 
            print(all_status_updates)
        elif status == "exit":
            break
status()


Solution

  • Several things, which might not work in your example:

    • You do not need to sort(), but to reverse the order of your list. For this you can use list slicing
    • You should not name the variable for user input status, which is the same name as the function
    def status():
    
        all_status_updates = []
        while True: 
            stat = input("Type Status Update Here...\n")
            if stat != "exit":
                all_status_updates.append(stat)
                print(all_status_updates[::-1])
            elif stat == "exit":
                break
    
    status()
    

    OUTPUT

    Type Status Update Here...
    a
    ['a']
    Type Status Update Here...
    b
    ['b', 'a']
    Type Status Update Here...
    c
    ['c', 'b', 'a']
    Type Status Update Here...
    d
    ['d', 'c', 'b', 'a']
    Type Status Update Here...
    e
    ['e', 'd', 'c', 'b', 'a']
    Type Status Update Here...
    f
    ['f', 'e', 'd', 'c', 'b', 'a']
    Type Status Update Here...
    exit