I have a list in a loop and I want to skip 3 elements after look
has been reached.
In this answer a couple of suggestions were made but I fail to make good use of them:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
for sing in song:
if sing == 'look':
print sing
continue
continue
continue
continue
print 'a' + sing
print sing
Four times continue
is nonsense of course and using four times next()
doesn't work.
The output should look like:
always
look
aside
of
life
I think, it's just fine to use iterators and
next
here:or, with exception handling (which is shorter as well as more robust as @Steinar noticed):
Of course you can use three time next (here I actually do it four time)
Then
for
usesiter(song)
to loop; you can do this in your own code and then advance the iterator inside the loop; callingiter()
on the iterable again will only return the same iterable object so you can advance the iterable inside the loop withfor
following right along in the next iteration.Advance the iterator with the
next()
function; it works correctly in both Python 2 and 3 without having to adjust syntax:By moving the
print sing
line up we can avoid repeating ourselves too.Using
next()
this way can raise aStopIteration
exception, if the iterable is out of values.You could catch that exception, but it'd be easier to give
next()
a second argument, a default value to ignore the exception and return the default instead:I'd use
itertools.islice()
to skip 3 elements instead; saves repeatednext()
calls:The
islice(song_iter, 3, 4)
iterable will skip 3 elements, then return the 4th, then be done. Callingnext()
on that object thus retrieves the 4th element fromsong_iter()
.Demo:
You can do this without an iter() as well simply using an extra variable:
Actually, using .next() three times is not nonsense. When you want to skip n values, call next() n+1 times (don't forget to assign the value of the last call to something) and then "call" continue.
To get an exact replica of the code you posted: