Home > Mobile >  why the sort function didn't work in this list?
why the sort function didn't work in this list?

Time:06-22

i am new to python programming and i am in a doubt in list data type. i used sort() function and it works for all the numbers i printed but not this numbers mentioned below. why?

a2=input("enter marks 2 :")
a3=input("enter marks 3 :")
a4=input("enter marks 4 :")
a5=input("enter marks 5 :")

marks=[a1,a2,a3,a4,a5]
print(marks)
marks.sort()
print(marks)```

>In terminal:
ter marks 1 :85
enter marks 2 :347
enter marks 3 :347
enter marks 4 :56
enter marks 5 :12
['85', '347', '347', '56', '12']
['12', '347', '347', '56', '85']

CodePudding user response:

You're trying sort strings, then it's working ok. But if you want consider like int, you will need parse to integer. Something like:

marks = [int(v) for v in marks]
marks.sort()
print(marks)

Or you can create a custom sort, using sorted:

marks = sorted(marks, key=lambda a: int(a))

CodePudding user response:

Your list is a list of strings so the sort() method is trying to sort them alphabetically. Use:

marks = [int(s) for s in marks]

then

marks.sort()

to order as integers.

Output:

enter marks 1 :85
enter marks 2 :347
enter marks 3 :347
enter marks 4 :56
enter marks 5 :12
['85', '347', '347', '56', '12']
[12, 56, 85, 347, 347]

CodePudding user response:

NOTE: there is a difference between list of strings and list of ints when we sort a list in python, the list of strings will be lexographically ordered and the list of numbers numerically ordered.

the problem is the type of the elements, to change that you can use list comprehension, map or simply iterating over the list.

in either way you have to convert the inputs into integers.

here are some ways you can achieve that.

  1. first method: list comprehension
marks=[a1,a2,a3,a4,a5]
marks = [int(mark) for mark in marks]
  1. second method: map function
marks=[a1,a2,a3,a4,a5]
marks = list(map(int,marks))
  1. third method: iterating
marks=[a1,a2,a3,a4,a5]
for i,x in enumerate(marks):
    marks[i] = int(x)

CodePudding user response:

This occurs because the sorting algorithm works differently on strings than on integers. input always returns a string, even if the inputted string is numeric. Lists of strings are sorted in lexicographic order – i.e. in ascending order by first digit, with ties broken by second digit if present, and so on.

Likely the best fix for this case is to replace each call of input(...) with int(input(...)). This ensures that all your a variables are integers, and so the marks list contains integers.

If you need marks to be a list of strings for some reason, you can still sort by numeric value by using marks.sort(key=int).

  • Related