2

I'm trying to get a function where if you do sort(listname) it would sort all the numbers inside that list from least to greatest.

I'm not sure whats wrong with mine, but I need some help as the output isn't actually least to greatest it does least to greatest for the first two numbers of the number.

Example :

If list has 23, 212, 44 in it than I sort it the output will be like this.

Output :

212,23,44

It should be 23, 44, 212.

Code:

def sort(my_list):
    size = len(my_list)
    for i in range(size):
        for j in range(size-i-1):
            if(my_list[j] > my_list[j+1]):
                tmp = my_list[j]
                my_list[j] = my_list[j+1]
                my_list[j+1] = tmp

More code :

numbers=([])
amount=input("How many numbers are in your list? ")
print("")
counter = 0
ran = 0
while counter < int(amount):
    counter = counter + 1
    ran = ran + 1
    num3 = input(str(ran) + ". Input: ")
    try:
       val = int(num3)
    except ValueError:
       num3 = input(str(ran) + ". Input: ")
    sort(numbers)
    numbers.append(num3)
0

3 Answers 3

4

That looks like your list doesn't contain any numbers but strings. Python doesn't try to guess what might be inside of those strings, so you get an odd sort order.

You have two options:

  1. Convert list elements to int before comparing them (if(int(my_list[j]) > int(my_list[j+1])):)
  2. Search this site for python natural sort to get answers how to implement "natural sorting" in Python.
Sign up to request clarification or add additional context in comments.

Comments

3

If you just want it sorted, use sorted:

sorted_my_list = sorted(my_list,key=int)

Or to sort it, in place, use

my_list.sort(key=int)

If you want to fix your program, turn my_list into ints or at least compare integers

if ( int(my_list[j]) > int(my_list[j+1])):

Also, you can swap two variables in one statement:

my_list[j],my_list[j+1] = my_list[j+1],my_list[j]

Comments

0

I just used your code (Just added a return statement). And it returns the expected values:

def sort(my_list):
    size = len(my_list)
    for i in range(size):
        for j in range(size-i-1):
            if(my_list[j] > my_list[j+1]):
                tmp = my_list[j]
                my_list[j] = my_list[j+1]
                my_list[j+1] = tmp
    return my_list # Note I added this return statement

print sort([23,212,44])
>>> 
[23, 44, 212]

1 Comment

I get this: 212,23,44... Weird.

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.