Also you are sorting array twice, I just corrected it.
values = [] sorted_values = [] data = 1 while data: data = input('Enter the values. Press enter to confirm values:') if data: values.append(data) else: data = data # here you are sorted it first and second outside of while loop sorted_values = sorted(values) print(sorted_values) print(sorted_values) with open("sortedvalues.txt", "a+") as name: name.write('\n' + str(sorted_values)) with open("sortedvalues.txt", "r") as open1: print('reading') print(open1.read())
inputs:
5 3 4 2 1 0
inside file:
[1, 2, 3, 4, 5]
Edit I should add that specifying the input as an integer results in a traceback because null (when the user presses enter to confirm the entered values) can not be parsed as an integer. To work around this, I simply added
while data:
data = input('Enter the values. Press enter to confirm values:')
if data:
values.append(int(data))
else:
data = data
print(sorted(values))
Last Updated : 03 Jun, 2022
Output:
Sorted list: [1, 2, 3, 4, 5] Reverse sorted list: [5, 4, 3, 2, 1] Original list after sorting: [1, 2, 3, 4, 5]
The sort() method is one of the ways you can sort a list in Python.,And there you have it! You now know how to sort a list in Python using the sort() method.,By the end, you will know the basics of sorting a list in Python and know how to customize the sorting to fit your needs.,To learn more about the Python programming language, check out freeCodeCamp's Scientific Computing with Python Certification.
The general syntax for the sort()
method looks like this:
list_name.sort(reverse = ..., key = ...)
The general syntax to do this would look something similar to the following:
list_name.sort()
Let's take a look at the following example which shows how to sort a list of whole numbers:
# a list of numbers my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54] #sort list in -place in ascending order my_numbers.sort() #print modified list print(my_numbers) #output #[3, 7, 8, 10, 11, 22, 33, 54, 100]
The general syntax to do this would look something like this:
list_name.sort(reverse = True)
Let's reuse the same example from the previous section, but this time make it so the numbers are sorted in reverse order:
# a list of numbers my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54] #sort list in -place in descending order my_numbers.sort(reverse = True) #print modified list print(my_numbers) #output #[100, 54, 33, 22, 11, 10, 8, 7, 3]