user8962187
user8962187

Reputation:

Next element in a for

I need to go to the next element of my for if a certain condition is true and restart my cycle from that element.

sets = [0,1,2,3]

for elem in sets:
    if (elem == 0)
       #next elem?

    ....
    ....

Upvotes: 0

Views: 1399

Answers (4)

Aaditya Ura
Aaditya Ura

Reputation: 12689

You can use generator :

Generators functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.

generator function don't start execution at the beginning of the function. Instead, the new call to a generator function will resume execution right after the yield statement in the code, where the last call exited.

your_list=[0,1,0,3]
def condition_loop(x):
    for i in x:
        if i==0:
            yield i
        else:
            yield 'x'

gen=condition_loop(your_list)
for i in range(len(your_list)):
    print(gen.__next__())

output:

0
x
0
x

Upvotes: 1

Dadep
Dadep

Reputation: 2788

continue could be a solution but you maybe do not need any thing :

>>> sets = [0,1,2,3]
>>> for elem in sets:
...     if (elem == 0):
...             print "the 0 element", elem
...     else:
...             print "other element", elem
... 
the 0 element 0
other element 1
other element 2
other element 3

Your for loop iterate trough all element of you list, if/elif/else condition maybe sufficient

Upvotes: 0

Ma0
Ma0

Reputation: 15204

There is nothing you have to do to go to the next element. The loop automatically iterates when the nested code has finished executing.

Example:

for elem in sets:
    if elem == 0:
       print(element)

will print all the elements that meet the condition; the sets will be exhausted.


Now, to force the loop to iterate even if the nested block has not finished executing yet, you can use continue.

Example:

for elem in sets:
    if elem == 0:
       print('found a 0!')
       continue
    print('Do you see me?')

In this case, whenever a 0 is found, the loop will terminate prematurely (without the 'Do you see me?' being print).

Upvotes: 1

Arjen Dijkstra
Arjen Dijkstra

Reputation: 1559

Use continue:

for elem in sets:
    if (elem == 0):
       continue

https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

Upvotes: 0

Related Questions