0

I was trying to sort list with added numbers but for some reason it doesn't work properly

def adding(numbers):
    numlist = []

    for x in range(numbers):
        numlist.append(input("Add number: "))

    return numlist


def how_many():

    amoun = int(input("How many numbers u wanna add: "))

    return amoun


def sort(to_sort):

    tempsort = 0

    for i in range(0, len(to_sort)):
        for j in range(i+1, len(to_sort)):
            if to_sort[i] > to_sort[j]:
                tempsort = to_sort[i]
                to_sort[i] = to_sort[j]
                to_sort[j] = tempsort

    print(to_sort)


lista2 = adding(how_many())

sort(lista2)

And the result is

How many numbers u wanna add: 5
Add number: 42
Add number: 2
Add number: 5
Add number: 78
Add number: 1
['1', '2', '42', '5', '78']
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 3
    You're sorting strings (that happen to contain numbers). The character '4' comes before '5' in a lexicographical sort. Convert the strings to numbers before sorting. For example: `int(input("Add number: "))` – jarmod Feb 23 '22 at 23:39
  • Do `lista2.sort(key=float)` if you want to sort a list of numeric strings according to their numeric value. – Samwise Feb 23 '22 at 23:46
  • 1
    btw, to swap two items Python lets you do `to_sort[i], to_sort[j] = to_sort[j], to_sort[i]` without needing a temporary variable! – Samwise Feb 23 '22 at 23:50

0 Answers0