1

I've been trying to make this work for some time now and I can't seem to get my list to sort out in ascending order. My program asks the user to enter three integers and then outputs results and is supposed to sort the numbers entered from least to greatest. However, whenever I try to sort it, it does not sort it the way I want to do. I've tried several ways of modifying the sort method, but it still does not work. For example, if I enter in 2, 10, and 5 as my three numbers, it will display it as "List: [2, 10, 5]".

import math

print ("")
print ("Welcome to my program!")
print ("")

v1 = input("Enter the first number: ")

print ("")

v2 = input("Enter the second number: ")

print ("")

v3 = input("Enter the third number: ")

print ("")

#tried to sort list here
list1 = [int(v1), int(v2), int(v3)]
sorted(list1, key=int)

sum = int(v1) + int(v2) + int(v3)
product = int(v1) * int(v2) * int(v3)
integer = int(v1)//int(v2)
mod = float(v1) % float(v2)
average = (float(v1) + float(v2) + float(v3))/ 3
star= "*"



print ("------------------")
print ("     RESULTS      ")
print ("------------------")
print ("")
print ("Sum: " + str(sum))
print ("")
print ("Product: " + str(product))
print ("")
print ("Integer Division: "+ str(integer))
print ("")
print ("Mod: " + str(mod))
print ("")
print ("Maximum Number: ", max(list1))
print ("")
print ("Minimum Number: ", min(list1))
print ("")
print ("Average: " + str(average))
print ("")
#outputs the list
print ("List: " + str(list1))
print ("")

print (v1 + " " + "".join([star] * int(v1)))
print (v2 + " " + "".join([star] * int(v2)))
print (v3 + " " + "".join([star] * int(v3)))

2 Answers 2

2

You need to assign to the sorted output:

srted  = sorted(list1) # creates a new list

To sort the original list sorting in place use list.sort:

list1.sort()  # sorts original list

You don't need to pass a key to sort ints.

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

Comments

2

sorted returns a value that you must reassign and the key is unnecessary:

list1 = [int(v1), int(v2), int(v3)]
list1 = sorted(list1)

Alternatively, you can call the sort method of the list which directly modifies it without return and reassignment:

list1 = [int(v1), int(v2), int(v3)]
list1.sort()

3 Comments

I will. It wouldn't let me until a few minutes goes by first. But I will as soon as it will let me :)
Answers are awarded based on value of a response. Your answer doesn't really have an explanation. And your answer was posted only seconds before mine.
You don't explain that sorted returns a value. Although it's implied, a more thorough explanation is necessary.

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.