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 Python Collections (Retired) Lists Redux Shopping List Take Three

bhaktipriya shridhar
bhaktipriya shridhar
2,350 Points

why do we need the for loop before the .insert() statement?

there is a for loop before the insert statement

for item in new_list: shopping_list.insert(spot,item.strip())

1.why do we need this for loop? can't we just write shopping_list.insert(spot,item.strip()) ,since we know the spot/index.

2.won't the shopping_list.insert(spot,item.strip()) get executed multiple times for every iteration of the for loop?

1 Answer

Bart Bruneel
Bart Bruneel
27,212 Points

Hello Bhaktipriya,

Suppose you put multiple items in your new_list. If we don't loop over the new_list and write .insert(spot, new_list) instead, we will just insert the whole list (as a complete list) into the shopping_list. This will give problems later on, I think, when we want to print our shopping_list. The .insert(spot, item.strip()) will be executed multiple times, one time for every item in our new_list. For example when the shopping_list is ['banana', 'pear'] and we would like to insert the new_list ['apple', 'peach'] into the shopping_list on spot 1, then we will first get ['banana', 'apple', 'pear'] on the first iteration and then ['banana', 'peach', 'apple', 'pear'] on the second iteration. If we don't include the for-loop but just write .insert(spot, new_list) we would get ['banana', ['apple','peach'], 'pear'].

bhaktipriya shridhar
bhaktipriya shridhar
2,350 Points

Thank you very much Bart! Your explanation has made my concept clear.