Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

.sort() function's underlying block

Hi!

This a-to-z sorter of the items in a list using the '<' quality (which works on the first letter of a string) seems like it should work in theory, but then returns "pizza", "pizza", "pizza" when I run it.

Would love some help from a better-placed-person to make a workable a-to-z sorter using a 'for' loop!

"""It seems like the 'for' loop is altering the string as it iterates, and so the iteration is "pizza" repeatedly."""

my_list = ["apple", "pizza", "Charlie", "David", "Banana"]

n = 0
for position in my_list:
    if (n+1+1)<=len(my_list):
        if position > my_list[n+1]:
            try:
                my_list.insert(n+2, position)
                my_list.pop(n+1)
            except IndexError:
                my_list.apppend(position)
                my_list.pop(n+1)
    n = n+1

print(my_list) 

[MOD: added ```python formatting. -cf]

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Modifying the for loop collection of items can have terrible side effects. Indices of items in the collection may no longer point to the next item in the list.

It is a valid exercise to work out sorting routines as this strengthens your understanding of CS problems and complexity of solutions. For reference, Python default sorting method is use timsort named after Tim Peters.

1 Answer

boi
boi
14,242 Points

Why on this beautiful planet Earth would anyone not just use the sort() method? Like literally it takes 1 line to sort:

my_list.sort()
print(my_list)

Anyway, I don't know about using for loops but you can use while loop.

my_list = ["Apple", "Pizza", "Charlie", "David", "Banana"]

sorted_list = []
while my_list:
    sorted_list.append(min(my_list))
    my_list.remove(min(my_list))


print(sorted_list)

P.S: I could not fix your solution, I feel it isn't realistic. If you figure it out make sure you tag me or post your solution here, It would be interesting for me to understand.

P.S.S: Let me know what you think.