Reputation: 69
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()
Upvotes: 0
Views: 6168
Reputation: 106
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
Upvotes: 9
Reputation: 3891
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()
Upvotes: 3
Reputation: 1807
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_)
Upvotes: 0