Search code examples
pythonstringinttypeerrorbubble-sort

Can't convert 'int' to string


I am trying to code the bubble sort algorithm and I am stumbling at the TypeError: Can't convert 'int' object to str implicitly and I have no clue as i've checked both x and length using isinstance() and they are both integers.

Here is my code so far:

x = 1
list1 = list(input("What numbers need sorting? Enter them as all one - "))
length = len(list1)
print(list1)
while True:
    for i in range(0,length):
        try:
            if list1[i] > list1[i+1]:
                x = list1[i]
                list1.remove(x)
                list1.insert(i+1,x)
                print(list1)
            if list1[i] < list1[i+1]:
                x += 1
                print(list1)
        except IndexError:
            break
    if x == length:
        print("The sorted list is - ",''.join(list1))
        break

Solution

  • The error is in the join(list1) call. str.join expects an iterable of strings. Your list1 is however a list of integers. So as a result it goes wrong.

    You can fix the error itself by mapping the elements of the list to the str equivalent, by writing:

    print("The sorted list is - ",''.join(map(str, list1))

    But that being said, the code is quite error prone:

    1. you add and remove items while iterating over the list;
    2. you use x both to count elements that are ordered, and to swap elements;
    3. you never reset x after a bubble loop, so you will count bubbles twice.
    4. furthermore catching the IndexError is quite inelegant, since you can also limit the range of i.

    Probably a more elegant solution is:

    unsorted = True
    while unsorted:
        unsorted = False  # declare the list sorted
                          # unless we see a bubble that proves otherwise
        for i in range(len(l)-1):  # avoid indexerrors
            if l[i] > l[i+1]:
                unsorted = True  # the list appears to be unsorted
                l[i+1], l[i] = l[i], l[i+1]  # swap elements
    
    print(l)  # print the list using repr