0

I'm a beginner programmer and I'm trying to make an exercise.

I want to sort an integer list, but every time I run my code, the list is not sorted. I've tried it in a couple of different ways with sorted() or .sort(), but nothing seems to help.

def main():

    _list1_ = []
    _list2_ = []

    print("Enter random numbers and enter Q to quit: ")
    userInput1 = input("")
    while userInput1.upper() != "Q":
        _list1_.append(int(userInput1))
        userInput1 = input("")

    print("Enter random numbers and enter Q to quit:")
    userInput2 = input("")
    while userInput2.upper() != "Q":
        _list2_.append(int(userInput2))
        userInput2 = input("")

    sorted(_list1_)
    sorted(_list2_)

    print(_list1_)

main()
2

3 Answers 3

9

sorted() doesn't sort the list in place. It returns the sorted list, so you will need to change the 2 sorted() calls to something like this:

_list1_ = sorted(_list1_)
_list2_ = sorted(_list2_)

It's always a good idea to read the documentation to get an understanding for how the functions work. Here is the docs for sorted https://docs.python.org/2/library/functions.html#sorted

Sign up to request clarification or add additional context in comments.

2 Comments

_list_1.sort() and _list2_.sort() will do it in place. Good to mention that.
Specially because sorted allocates a new list, so it takes extra memory.
3

sorted returns the sorted list whereas sort performs the sort in place.

So you could either do:

_list1_ = sorted(_list_)

or:

_list1_.sort()

If you were to use sort (my preferred method) your code would look like this:

def main():

    _list1_ = []
    _list2_ = []

    print("Enter random numbers and enter Q to quit: ")
    userInput1 = input("")
    while userInput1.upper() != "Q":
        _list1_.append(int(userInput1))
        userInput1 = input("")

    print("Enter random numbers and enter Q to quit:")
    userInput2 = input("")
    while userInput2.upper() != "Q":
        _list2_.append(int(userInput2))
        userInput2 = input("")

    _list1_.sort()
    _list2_.sort()

    print(_list1_)

main()

Comments

0
sorted(_list1_) 

returns a list after sorting list1, It does not sort the list1. so write

print(sorted(_list1_)) 

or assign the sorted list1 to list1, like

_list1_ = sorted(_list1_)

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.