What is the pythonic way of looping through a range of numbers and skipping over one value? For example, the range is from 0 to 100 and I would like to skip 50.
Edit: Here's the code that I'm using
for i in range(0, len(list)):
x= listRow(list, i)
for j in range (#0 to len(list) not including x#)
...
You can use a continue statement in Python to skip over part of a loop when a condition is met. Then, the rest of a loop will continue running. You use continue statements within loops, usually after an if statement.
The break statement can be used if you need to break out of a for or while loop and move onto the next section of code. The continue statement can be used if you need to skip the current iteration of a for or while loop and move onto the next iteration.
Use the continue statement inside the loop to skip to the next iteration in Python. However, you can say it will skip the current iteration, not the next one.
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
You can use any of these:
# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
print i
# Create 2 ranges [0,49] and [51, 100] (Python 2)
for i in range(50) + range(51, 100):
print i
# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
print i
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print i
In addition to the Python 2 approach here are the equivalents for Python 3:
# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
print(i)
# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
print(i)
# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
print(i)
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print(i)
Ranges are lists in Python 2 and iterators in Python 3.
It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:
import itertools
m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
print(i) # skips m = 5
As an aside, you woudn't want to use (*range(m), *range(m + 1, n))
even though it works because it will expand the iterables into a tuple and this is memory inefficient.
Credit: comment by njzk2, answer by Locke
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With