0

I don't understand why 'phone case' does not get added if I change the while loop to a for loop.

unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []

while unprinted_designs:
    current_design = unprinted_designs.pop()
    print(f"Printing Model: {current_design}")
    completed_models.append(current_design)

I changed it to a for loop.

for design in unprinted_designs:
    current_design = unprinted_designs.pop()
    print(f"Printing Model: {current_design}")
    completed_models.append(current_design)

  • Don't change a list while (`pop`) you're iterating over it, it messes things up – G. Anderson Nov 12 '20 at 23:12
  • So you are telling us that if you replace while loop with for loop and change nothing else in the programs this ads the other two strings in unprinted_designs but not the first one? – YourHelper Nov 12 '20 at 23:12
  • https://stackoverflow.com/questions/13939341/why-does-a-for-loop-with-pop-method-or-del-statement-not-iterate-over-all-list?noredirect=1&lq=1 explains it really well but essntially your index for your interator keeps advancing while you are still popping off the last element each time. by the time you get to `robot pendant`, your index is already at the last element and you have no more iterations left. – Karan Nov 12 '20 at 23:20
  • @YourHelper if you pop the from the list while iterating with a for loop, the indexes of the list doesn't match up any longer, since the list has shifted one element – CoffeDev Nov 12 '20 at 23:21

0 Answers0