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
Kathleen Rauh
1,785 PointsList prints endlessly. Why?
shopping_list = []
print("What should we get at the store? ")
print("Enter 'DONE' to stop adding items.")
while True:
new_item = input ("> ")
if new_item == 'DONE':
break
shopping_list.append(new_item)
print("Added! List has {} items.".format(len(shopping_list)))
continue
print("Here's your list:")
for item in shopping_list:
shopping_list.append(item)
print(shopping_list)
2 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi Kathleen,
Here's your for loop:
for item in shopping_list:
shopping_list.append(item)
print(shopping_list)
You're getting an endless loop because you're modifying shopping_list in your loop. Specifically, you're adding each item onto the end of the list. In general, you don't want to modify the iterable that you're iterating over in a loop.
This means your list is getting bigger by one each time through the loop. The for loop can never reach the end of the list since it keeps growing.
By the time you reach the for loop your shopping list already has all the items in it so you don't want to append them again onto the end of the list. Inside the loop you probably only want to print each item instead of the entire list. print(item)
Let me know if that doesn't make sense.
Kathleen Rauh
1,785 PointsThank you! i can't believe I didn't realize I had already appended to the list!