Ask Your Question
1

How to skip a single loop iteration

asked 2018-07-05 19:30:36 -0500

MarioM gravatar image

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 flag offensive close merge delete

3 answers

Sort by ยป oldest newest most voted
0

answered 2018-07-06 06:49:10 -0500

vdelecroix gravatar image

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
edit flag offensive delete link more
0

answered 2018-07-06 03:23:48 -0500

joaoff gravatar image

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
edit flag offensive delete link 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)
vdelecroix gravatar imagevdelecroix ( 2018-07-06 05:19:26 -0500 )edit
0

answered 2018-07-06 05:11:36 -0500

dan_fulea gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 2018-07-05 19:30:36 -0500

Seen: 34 times

Last updated: Jul 06