Introduction:
So I know that there is already a question (Skip multiple iterations in loop) similar to mine with a really good answer, but there are still some open questions for me:
Question 1:
Is there any way of doing it without an iterator?
I am looking for something like * 3:song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
for sing in song:
print(sing, end=" ")
if sing == 'look':
continue * 3
expected output:
always look side of life
Question 2:
If I have to use an iterator object, then is it possible to do it a fixed amount of time?
The original question has a solution like this:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print(sing)
if sing == 'look':
next(song_iter)
next(song_iter)
next(song_iter)
print(next(song_iter))
But I want it to do it let's say x = 5 times. It is not possible like this:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print(sing)
if sing == 'look':
next(song_iter) * x
print(next(song_iter))
So how would you do it? I know it is possible to use the function itertools.islice
, but is there a way without any libraries?
My Approach:
This works great:song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
skip_iterations = 3
for sing in song_iter:
print(sing)
if sing == "look":
while skip_iterations > 0:
next(song_iter, "")
skip_iterations -= 1
Output:
always look side of life
But maybe anyone else has a better idea? :)
Links:
The Question I was mentioning - The Answer for that question