Python Program to Implement Gnome Sort

This is a Python program to implement gnome sort.

Problem Description

The program sorts a list by gnome sort.

Problem Solution

1. Create a function gnome_sort that takes a list as argument.
2. Inside the function create a loop with loop variable pos that iterates from 1 to the length of the list – 1.
3. Inside the loop, create a while loop that runs as long as pos != 0 and alist[pos] and alist[pos – 1] are out of order.
4. In the body of the while loop, swap alist[pos] and alist[pos – 1] and decrement pos.

Program/Source Code

Here is the source code of a Python program to implement gnome sort. The program output is shown below.

def gnome_sort(alist):
    for pos in range(1, len(alist)):
        while (pos != 0 and alist[pos] < alist[pos - 1]):
            alist[pos], alist[pos - 1] = alist[pos - 1], alist[pos]
            pos = pos - 1
 
 
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
gnome_sort(alist)
print('Sorted list: ', end='')
print(alist)
Program Explanation

1. The user is prompted to enter a list of numbers.
2. The list is passed to the gnome_sort function.
3. The sorted list is displayed.

advertisement
Runtime Test Cases
Case 1:
Enter the list of numbers: 2 3 2 51 38 1 10 3 0 7 8
Sorted list: [0, 1, 2, 2, 3, 3, 7, 8, 10, 38, 51]
 
Case 2:
Enter the list of numbers: 5 4 3 2 1
Sorted list: [1, 2, 3, 4, 5]
 
Case 3:
Enter the list of numbers: 7
Sorted list: [7]

Sanfoundry Global Education & Learning Series – 1000 Python Programs.

If you wish to look at all Python Programming examples, go to 1000 Python Programs.

🎓 Free Certifications on 300 subjects are live for January 2026. Register Now!

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels

advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations