break for loop in Python

Question:

is it possible to break a for loop in Python, without break command?
I’m asking this question in order to compare it with C++ for loop, in which actually checks a condition each time.

i.e. it’s possible to break a for loop in C++ like below:

for(int i=0; i<100; i++)
    i = 1000; // equal to break;

is it possible to do the same in Python?

for i in range(0,100):
    i = 10000 // not working
Asked By: MBZ

||

Answers:

Python’s for is really a "for each" and is used with iterables, not loop conditions.

Instead, use a while statement, which checks the loop condition on each pass:

i = 0
while i < 1000:
    i = 1000

Or use an if statement paired with a break statement to exit the loop:

for i in range(1000):
    if i == 10:
        break
Answered By: Raymond Hettinger

Use a while loop for that purpose:

i = 0
while i < 100:
    i = 1000
Answered By: Sufian Latif

This won’t work (as you’ve noticed). The reason is that, in principle, you are iterating the elements of a list of ascending numbers (whether that is really true depends on if you’re using python 2 or 3). You can use the ‘break’ keyword to break out of a loop at any time, although using it in excess might make it hard to follow your code.

Answered By: FatalError

No, for doesn’t work like that in Python. for iterates over a list (in this case) or other container or iterable. for i in range(0, 100) doesn’t mean “increment i until i is greater than or equal to 100″, it means “set i to successive items from a list of these 100 items until the list is exhausted.”

If i is 50, then the next item of the list is still 51, regardless of what you may set i to.

break is better anyway.

Answered By: kindall

You might have to settle for the break statement:

http://docs.python.org/tutorial/controlflow.html

for i in range(0,100):
    print i
    if i == 10:
        break
Answered By: Andy Arismendi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.