How to Bubble Sort Numbers in Python

The following python program uses the bubble algorithm to sort a list of numbers. The program allows the user to input the list of numbers from the console. Please note that bubble sort is a very inefficient algorithm and hence is not recommended in production code with large data.

# Bubble sort in python
# Sorts numbers in ascending order
str_input = input("Please enter numbers separated by spaces: ")

# split the string into numbers & create a list of numbers
numbers = [int(x) for x in str_input.split()]

count = len(numbers)

for outer in range(count-1): # bubbles each number to the end
    for i in range(count-outer-1):
        if numbers[i] > numbers[i+1]:
            # swap numbers!
            numbers[i],numbers[i+1] = numbers[i+1],numbers[i]


The above program asks the user to enter a list of numbers separated by spaces. This is split into individual numbers using the split() function and then converted to a list of numbers using the int() function and list comprehension.

The program then uses two nested loops to sort the numbers. The outer loop runs as many times as the numbers in the list. For each inner loop iteration, the largest number is bubbled to the right. Hence for each outer loop iteration, we get the next large number bubbled to the right.  Note that we are using a tuple assignment in python to swap two values in the list. There is no need for a temporary variable for swapping variable values.

Here is the sample output from the program,

Please enter numbers separated by spaces: 8 129 22 42 22 1
[1, 8, 22, 22, 42, 129]