Home > database >  for each loop pyton - nested loop
for each loop pyton - nested loop

Time:02-06

lyrics = ["I want to break free", "I want to break free",
          "I want to break free", "yes, I want to break free"]
number_of_lines = 6

I am trying to create a loop that prints as many lines as many number_of_lines. In this specific example I basically need to loop IN lyrics 1.5 times to print the whole list (4 lines) and then the first 2 again to get to 6 = number of lines. How do you do it exactly?

thanks much in advance

for line in lyrics:
   print(line)

CodePudding user response:

You could use the module operator as follows:

lyrics = ["I want to break free", "I want to break free", "I want to break free", "yes, I want to break free"]
number_of_lines = 6

for i in range(number_of_lines):
    print(lyrics[i%len(lyrics)])

Output:

I want to break free
I want to break free
I want to break free
yes, I want to break free
I want to break free
I want to break free

CodePudding user response:

Use itertools.cycle to repeat the contents of the list as often as necessary to obtain the desired number of lines (using itertools.islice):

from itertools import cycle, islice


lyrics = ["I want to break free", "I want to break free",
          "I want to break free", "yes, I want to break free"]
number_of_lines = 6

for line in islice(cycle(lyrics), 6):
    print(line)

(I believe this incurs some additional memory overhead, though. cycle has to cache the values it reads from its iterator in order to repeat them, and I'm not sure it's optimized to recognize when it's using a list iterator that can repeatedly read from the given list argument. Just something to keep in mind when using cycle and large lists, but typically the lists will be small.)

CodePudding user response:

Another option (maybe a bit more "Pythonic" as using the module operator) is to use the cycle() method available in the with Python coming itertools module as follows:

lyrics = ["I want to break free", "I want to break free", "I want to break free", "yes, I want to break free"]
number_of_lines = 6

from itertools import cycle
lyrics_cycle = cycle(lyrics)

for _ in range(number_of_lines):
   print( next(lyrics_cycle) )

And because lyrics_cycle is an iterator you get a line out of it using the Python next() method and don't need the index value provided in the loop by range().

  • Related