# Sort in ascending order in List

Hi Everyone,

I’m new in Python, below is my program. Want to understand, why ascending order I don’t see when printing.

a=
x=int(input("Enter max value: "))
for i in range(x):
values=input(“Entetr values”)
a.append(values)
print(a)
a.sort(reverse=False)
print(a)
print(“Max value in a list:”,max(a))
print(“Min value in a list is:”,min(a))

Results:

Enter max value: 5
Entetr values2
Entetr values88
Entetr values33
Entetr values2
Entetr values6
[‘2’, ‘88’, ‘33’, ‘2’, ‘6’]
[‘2’, ‘2’, ‘33’, ‘6’, ‘88’] >>>>>>>>>>>>> This result is not in ascending order, 2,2,6,33,88 ?
Max value in a list: 88
Min value in a list is: 2

when I run it, then it does return a sorted list,

``````a = []
x = int(input("Enter max value: "))
for i in range(x):
values = input('Enter values: ')
a.append(values)
print(a)
a.sort(reverse=False)
print(a)
print('Max value in a list:', max(a))
print('Min value in a list is:', min(a))
``````

gives,

``````Enter max value: 5
Enter values: 3
Enter values: 4
Enter values: 1
Enter values: 2
Enter values: 6
['3', '4', '1', '2', '6']
['1', '2', '3', '4', '6']
Max value in a list: 6
Min value in a list is: 1
``````

it appears that it gives lexicographically sorted list,
we could use `key=int` to convert strings to integers while sorting,

``````a.sort(reverse=False, key=int)
``````
1 Like

because you have not converted them to integers.
This is sorted lexicographically. Convert each value to integer using `int()`

``````a = []
x = int(input("Enter max value: "))
for i in range(x):
values = int(input('Enter values: '))
a.append(values)
print(a)
a.sort(reverse=False)
print(a)
print('Max value in a list:', max(a))
print('Min value in a list is:', min(a))
``````

Yes, it is in ascending order. It is in ascending order for strings, which uses lexicographic or dictionary order.

‘88’ comes before ‘9’ in the dictionary, because the first character ‘8’ comes before ‘9’.

Just like “House” comes before “Ice” because H comes before I.

Lexicographic order goes 0123…89ABC…XYZabc…xyz and matches alphabetical order for English (but not necessarily for all other languages).

If you need to sort in numeric order, where 9 is smaller than 88, you need to convert the strings returned by `input()` into ints.

``````value = input("Enter value")
a.append(int(value))``````
1 Like