Python Forum
Old brain - New Language - Question on loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Old brain - New Language - Question on loops
#7
The for loop is basically syntactic sugar for a while loop, and this is one of the ways where the underlying method makes itself visible. The for loop keeps track of what position it's currently at in the list, and increases that each time. So if you change the list while looping over it, you get weird results (like you're seeing).

Sort of like this:
>>> guests = ['Geoff', 'Colin', 'David', 'Adolf', 'Charles', 'Fred']
>>> index = 0
>>> while index < len(guests):
...   current = guests[index]
...   index += 1
...   removed = guests.pop()
...   print(f"Iteration: {index}\tRemoved: {removed}\tRemaining: {guests}")
...
Iteration: 1    Removed: Fred   Remaining: ['Geoff', 'Colin', 'David', 'Adolf', 'Charles']
Iteration: 2    Removed: Charles        Remaining: ['Geoff', 'Colin', 'David', 'Adolf']
Iteration: 3    Removed: Adolf  Remaining: ['Geoff', 'Colin', 'David']
Reply


Messages In This Thread
RE: Old brain - New Language - Question on loops - by nilamo - Oct-03-2018, 08:27 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to fix my brain on classes blackknite 2 1,245 May-01-2022, 12:25 PM
Last Post: ibreeden
  Back to loops question wernerwendy 1 2,915 Jun-17-2017, 10:02 PM
Last Post: ichabod801
  Question on runtime and improving nested for loops ackmondual 1 3,084 Jun-13-2017, 11:11 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020