0

Homework: Self teaching out of a book. Still very much a novice

I create a list then print that list out using a For-Loop. It works fine.

guests=["John","Jeff","Jack","Mom"]

for i in range(len(guests)):
    print(f"I would like to invite you, {guests[i]}, to dinner.")

Now I recreate this same thing but am removing everyone from the list.

for i in range(len(guests)):
    person=guests.pop(i)
    print(f"Sorry {person}, dinner has been canceled.")

This is where it goes wrong. The code increments by 2 then says pop index out of range. If it starts at 0 and goes for the length 0,1,2,3 then why is it jumping by 2s?

  • 2
    Related: [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) and [How to remove items from a list while iterating](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating). – jarmod Sep 19 '22 at 17:53
  • 2
    @jarmod I think that's the dup I was looking for. – 001 Sep 19 '22 at 17:56
  • im trying to use the pop method as to print the popped out name. I do understand remove or even del works fine, yet it is the pop() feature I am attempting to learn. Then to understand why it is going in increments of 2 and not 1 – CooperFlats Sep 19 '22 at 18:01
  • 2
    @JohnnyMopp yes, it's quite hard to find some of the canonical questions on SO. Especially under time pressure to be the first ;-) The in-built SO search is not the best option, in my experience. – jarmod Sep 19 '22 at 18:02
  • @CooperFlats pop() alters the length of the list. so len(list) = 4 list.pop(0), len(list)=3 – d6stringer Sep 19 '22 at 18:02
  • !! I see, how simple. thank you – CooperFlats Sep 19 '22 at 18:06
  • solved it by not incrementing pop. Thank you dbstringer for that nudge. solution came to be:: for i in range(len(guests)): person = guests.pop(0) print(f"Sorry {person}, the dinner is canceled.") – CooperFlats Sep 19 '22 at 18:39
  • If you're going to do that then you could simply do: `while guests: print(guests.pop(0))` – jarmod Sep 19 '22 at 19:44

0 Answers0