9.More with 'for' infinite loop


#1

im currently stuck on this exercise. If i run it it says that the program is in an infinite loop but i dont know why.

Heres my code:

start_list = [5, 3, 1, 2, 4]
square_list = []

for number in start_list:
    start_list.append(number ** 2)
    start_list.sort()
print square_list

link to exercise: https://www.codecademy.com/courses/python-beginner-en-pwmb1/1/6?curriculum_id=4f89dab3d788890003000096#


#2

you are appending items to the list you are looping over, this means the list becomes longer, thus the loop needs to loop over more items, thus the list becomes longer, thus the loop needs to loop over more items and so on till infinity

try appending to square_list instead


#3

worked! Thank you very much


#4

you could also sort the list after the for loop has finished running, and not every run of the loop? just a small optimization.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.