In this article, we will show you, How to write a Python Program to Sort List items using Bubble sort with practical example.

**TIP:** Please refer List article to understand everything about Lists.

## Python Program for Bubble Sort using For Loop

This Python program allows the user to enter the List Size. Next, we are using For Loop to insert elements into the List

# Python program for Bubble Sort a = [] number = int(input("Please Enter the Total Number of Elements : ")) for i in range(number): value = int(input("Please enter the %d Element of List1 : " %i)) a.append(value) for i in range(number -1): for j in range(number - i - 1): if(a[j] > a[j + 1]): temp = a[j] a[j] = a[j + 1] a[j + 1] = temp print("The Sorted List in Ascending Order : ", a)

**OUTPUT**

**ANALYSIS**

Here, we are using Nested For Loop to iterate each and every element in a given List. Inside the loop we are using If statement to sort items in an ascending order using Bubble Sort.

**First For Loop – First Iteration: **for o in range (3)

The condition is True so, it will enter into second for loop

**Second For Loop – First Iteration:** for o in range(4 – 0 – 1)

Condition inside the For Loop is True so, compiler will enter into the If Statement

if(a[0] > a[1]) => if(10 > -4) – It means, Condition is True

temp = 10

a[j] = a[j + 1] => a[0] = a[1] => a[0] = -4

a[j + 1] = temp => a[1] = 10

Now the List will be **-4 10 10 5**.

**Second For Loop – Second Iteration:** for 1 in range(4 – 0 – 1) – True

if(10 > 10) – It means, Condition is False

Do the same for the remaining Iterations

## Python Program for Bubble Sort using While Loop

This program is same as above. However, we replaced the for loop with While Loop to sort list elements using bubble sort

# Python program for Bubble Sort a = [] number = int(input("Please Enter the Total Number of Elements : ")) for i in range(number): value = int(input("Please enter the %d Element of List1 : " %i)) a.append(value) i = 0 while(i < number -1): j = 0 while(j < number - i - 1): if(a[j] > a[j + 1]): temp = a[j] a[j] = a[j + 1] a[j + 1] = temp j = j + 1 i = i + 1 print("The Sorted List in Ascending Order : ", a)

**OUTPUT**

## Python Program for Bubble Sort using Functions

This is same as the first example, but we separated the logic to sort list elements using Functions.

# Python program for Bubble Sort def bubblesort(a, number): for i in range(number -1): for j in range(number - i - 1): if(a[j] > a[j + 1]): temp = a[j] a[j] = a[j + 1] a[j + 1] = temp a = [] number = int(input("Please Enter the Total Number of Elements : ")) for i in range(number): value = int(input("Please enter the %d Element of List1 : " %i)) a.append(value) bubblesort(a, number) print("The Sorted List in Ascending Order : ", a)

**OUTPUT**