Ask Your Question

# How to skip a single loop iteration

I have the following code:

 for k in range(9):
if k != 3:
print(k)
else:
print(20)
# i want to skip the next iteration


So I want to get: 0,1,2,20,5,6,7,8, here I skip the fourth iteration. I already try to use the command next(), but it doesn't give what I want

edit retag close merge delete

## 3 Answers

Sort by ยป oldest newest most voted

Is that all you want?

One way to do that.

for k in range(9):
if k != 3:
if k != 4:
print(k)
else:
pass
else:
print(20)
# i want to skip the next iteration

more

## Comments

the

else:
pass


can be removed... the whole thing is equivalent to

for k in range(9):
if k != 3:
print(k)
elif k != 4:
print(20)

( 2018-07-06 12:19:26 +0200 )edit

The following

R = iter(range(9))
for r in R:
if r == 3:
a = next(R)   # remove the next element from the iterator
print(r)


produces

0
1
2
3
5
6
7
8

more

Depending on the real need, the one or the other of the following code snippets may be preferable.

(1) Arrange the range.

R = [0..2] + [20] + [5..8]
for r in R:
print r


(2) Define a function that does the right thing for the right k:

def f(k):
if k == 3:    print 20
elif k == 4:    pass
else:    print k

for k in [0..8]:
f(k)


(3) Do the same as above without function.

for k in [0..8]:
if k == 4:    continue
elif k == 3:    print 20
else:    print k


(4) If in the real application we have no good control of the position, after that we skip, we can use a flag, skipNext say...

def myCondition(k): if k == 3: return True return False

nextSkip = False for k in range(9): oldSkip = nextSkip nextSkip = myCondition(k) if oldSkip: continue if nextSkip: print 20 else: print k

You see how hard is to guess the "needed solution". The question is a pure python question, consider reviewing data structures in python and logical ramification possibilites.

more

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2018-07-06 02:30:36 +0200

Seen: 589 times

Last updated: Jul 06 '18