Python Forum
Question about for loop not creating an infinite loop.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about for loop not creating an infinite loop.
#2
The pop method removes the last item from the list, as well as returning that item. So the first loop shrinks the list by one before growing it by one, thus keeping it the same size. The second one has no pop, so items are not removed (iterating with a for loop does not remove items from the list).

Note that modifying a list while you are iterating over it is a bad idea. It works out in the code above, but it doesn't always. A better way to do what your exercise wants is to build a new list:

great_magicians = []
for magician in magicians:
    the_great = 'the great {}'.format(magician)
    great_magicians.append(the_great)
    print(great_magicians)
The format method of strings is recommended over string addition for efficiency reasons. In 3.6 or later, look into f-strings.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
RE: Question about for loop not creating an infinite loop. - by ichabod801 - Feb-03-2019, 08:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop through all files in a directory? Winfried 10 316 Apr-23-2024, 07:38 PM
Last Post: FortuneCoins
  for loop not executing Abendrot47 2 209 Apr-09-2024, 07:14 PM
Last Post: deanhystad
  Re Try loop for "net use..." failures tester_V 10 606 Mar-02-2024, 08:15 AM
Last Post: tester_V
  File loop curiously skipping files - FIXED mbk34 10 801 Feb-10-2024, 07:08 AM
Last Post: buran
  Optimise multiply for loop in Python KenBCN 4 488 Feb-06-2024, 06:48 PM
Last Post: Gribouillis
  Basic binary search algorithm - using a while loop Drone4four 1 368 Jan-22-2024, 06:34 PM
Last Post: deanhystad
  loop through csv format from weburl in python maddyad82 3 408 Jan-17-2024, 10:08 PM
Last Post: deanhystad
  Variable definitions inside loop / could be better? gugarciap 2 441 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  UART & I2C slow down a loop trix 4 620 Dec-28-2023, 05:14 PM
Last Post: trix
  Need an alternative to brute force optimization loop jmbonni 5 1,180 Dec-07-2023, 12:28 PM
Last Post: RockBlok

Forum Jump:

User Panel Messages

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