Is there a way to sort an empty list of strings as you add more values to the list? I cannot find a decent example of this anywhere and struggling with this.

The insertion sort seemed like the logical plan, but I cannot for the life of me find anything regarding this. Not even my textbook.

an example I found

def insertion_sort ( lista ):
  for i in range ( 1, len ( lista ) ):
    save = lista[i]
    j = i
    while ( j > 0 and lista [j - 1] > save ):
      lista[j] = lista[j - 1];
      j -= 1
    lista[j] = save

^^ is the only idea i have, yet I do not know what is happening in the code

Recommended Answers

All 3 Replies

A temporary test print might shed some light on the workings of the code ...

def insertion_sort( lista ):
    for i in range ( 1, len( lista ) ):
        save = lista[i]
        j = i
        while ( j > 0 and lista[j - 1] > save ):
            lista[j] = lista[j - 1];
            j -= 1
        lista[j] = save
        # optionally show sort progress
        print( lista )


lista = ['j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
insertion_sort(lista)

''' my result>>>
['i', 'j', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
['h', 'i', 'j', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
['g', 'h', 'i', 'j', 'f', 'e', 'd', 'c', 'b', 'a']
['f', 'g', 'h', 'i', 'j', 'e', 'd', 'c', 'b', 'a']
['e', 'f', 'g', 'h', 'i', 'j', 'd', 'c', 'b', 'a']
['d', 'e', 'f', 'g', 'h', 'i', 'j', 'c', 'b', 'a']
['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'b', 'a']
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'a']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
'''

Actually, you can use Python module bisect to do just what you want ...

# using module bisect to insert a string into a sorted
# list of strings at the correct position

import bisect

name_list = ['Eva', 'Pam', 'Dee', 'Amy', 'Gin', 'Joy', 'Mae']
# binary searches require a sorted list
name_list.sort()

print(name_list)

# insert a new name at the correct position in the list
new_name = 'Kay'
bisect.insort_left(name_list, new_name)

print(name_list)

''' my result>>>
['Amy', 'Dee', 'Eva', 'Gin', 'Joy', 'Mae', 'Pam']
['Amy', 'Dee', 'Eva', 'Gin', 'Joy', 'Kay', 'Mae', 'Pam']
'''

Thanks vegaseat! Would have never thought of bisect. Cheers

You are welcome!

As I have said many times, Python's basic syntax is easy to learn, the difficult part is to know what all those wonderful modules can do for you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.