I have written the below bubble sort code in Python.

def bubble_sort():
    list_cnt=input("How many numbers you would like to sort:")
    for i in range(int(list_cnt)): ### need to convert the value returned by input()
        num_list.append(input("Enter " +str(i)+" number:")) ##here we are using append method of list

    print("The values input are as follows:")

    ### Below new line of code added to convert list to integer###
    ## with the above line the code is now working as expected##
    max_index=len(num_list)-1 ## because list begins with 0
    print("max_index is:",max_index)
    for i in range(len(num_list)-1):
        for j in range(len(num_list)-1):
            if num_list[j] > num_list[j+1]:
                print("Sorted when j=" +str(j)+ " and i=" + str(i)+ " is:\n ")
        if not swapped:

    print("The sorted list is :")


Your code's quite good. I'd however change it in the following ways:

  1. Move the creation of the lits out of the buble_sort.
  2. Remove the prints from buble_sort.
  3. Follow PEP8.
  4. Change for i in range(...) to while True:.
  5. Use better variables. num_list to array could do.
  6. Use str.format, rather than string addition.
  7. Change the creation of num_list to use a list comprehension.
def bubble_sort(array):
    while True:
        swapped = False
        for j in range(len(array)-1):
            if array[j] > array[j+1]:
                array[j], array[j+1] = array[j+1], array[j]
                swapped = True
        if not swapped:

if __name__ == '__main__':
    amount = input("How many numbers you would like to sort:")
    array = [
        int(input("Enter {} number:".format(i)))
        for i in range(int(amount))

    print("The values input are as follows: {}".format(array))
    print("The sorted list is: {}".format(array))
  • 4
    \$\begingroup\$ I agree with everything except renaming num_list to array, since it is a list, not an array. numbers would probably be better, since it explains what it contains, and implies that it is a sequence without stating a concrete type. \$\endgroup\$ – Raimund Krämer Apr 25 '18 at 13:43
  • \$\begingroup\$ @RaimundKrämer You could use list however that shadows list. They're also IIRC arrays with list interfaces, so it's simpler to call it a list. Also we're only using it for it's array interface. But yeah numbers could work. \$\endgroup\$ – Peilonrayz Apr 25 '18 at 13:45

The IO code is mixed with the logic code. I separated them. Also, I made a few other changes including removing useless comments (the code should speak for itself, your comments don't add much; if you need comments, that probably means you should simplify your code). I also converted the numbers as soon as they are input.

def bubble_sort(num_list):
    for i in range(len(num_list)-1):
        swapped = False
        for j in range(len(num_list) - 1):
            if num_list[j] > num_list[j+1]:
                num_list[j], num_list[j+1] = num_list[j+1], num_list[j]
                swapped = True
        if not swapped:

def main():
    num_list = []
    num_items = int(input("How many numbers you would like to sort:"))
    for i in range(num_items):
        num_list.append(int(input("Enter " + str(i + 1) + "st number:")))
    print("The sorted list is:")

if __name__ == '__main__':
  • \$\begingroup\$ @Gal Sapir FWIW, I think the redundant assignment was copied from the original, but it is a valid improvement AFAICT \$\endgroup\$ – Solomon Ucko Jan 27 at 20:18
def bubble(items):
    num = len(items)
    for scan in range(num-1):
        swaped = False
        #takes care of the scanning through the array
        for swap in range(num-1-scan):
            if items[swap]>items[swap+1]:
                temp_var = items[swap]
                swaped = True
            if swaped == True:
items = [90,23,95,56]
print("sorted itema are:",items)
  • 2
    \$\begingroup\$ Welcome to Code Review! Unfortunately this post doesn't really offer much for the OP in terms of his/her code. Please (re-) read The help center page How do I write a good answer?. Note it states: "Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted." \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Sep 4 '20 at 4:37
  • 1
    \$\begingroup\$ The code produces a syntax error when copied from above code block and pasted into a Python interpreter. The items are not put out in non-decreasing order even for the embedded example. Output and code contain spelling errors. \$\endgroup\$ – greybeard Sep 4 '20 at 5:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.