Skip over a value in the range function in python
Asked Answered
S

11

78

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#)
        ...
Shillelagh answered 6/6, 2014 at 20:11 Comment(3)
The continue statement with a conditional?Trelliswork
I could do that but is there any way to get it in the structure of the loop itself?Shillelagh
what are you doing in the loop?Thessa
M
109

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
Meredithmeredithe answered 6/6, 2014 at 20:18 Comment(8)
The third suggestion throws TypeError because you did not explicitly create an iteratorScopolamine
(1) creates two lists, (2) concatenates two lists, (3) does not work, xrange is not a iterator. (4) should use xrange to avoid creating a list, and is the so far best solution.Lubricious
How does (1) create two lists? xrange(100) is not a list. And you can avoid creating the second list by returning a generator instead: for i in (x for x in xrange(100) if x is not 50)Scopolamine
@Daniel: 1/ creates one list only because of xrange. 2/ I know, not the most efficient, but clear. 3/ typo, thanks for pointing out 4/ probably, yes. (but for a 100 elements it is fine)Meredithmeredithe
#2 with Python 3.x: ...list(range(50)) + list(range(51, 100)):Abortifacient
@Abortifacient or using itertools.chain(range(50), range(51, 100)) instead, to avoid creating lists (although my initial solution is indeed creating 2 lists)Meredithmeredithe
#2 doesn't work in Python 3. The rest are all quite inefficient.Aggravation
@Acumenus this question is tagged python, not python3. If you have more efficient solutions, please share them so everyone can benefit :)Meredithmeredithe
V
14

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.

Vitric answered 6/10, 2018 at 15:9 Comment(0)
A
2

If the index of the skipped value is known, it is not necessary to compare each number:

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

Aggravation answered 10/9, 2019 at 14:20 Comment(0)
R
1
for i in range(0, 101):
    if i != 50:
        do sth
    else:
        pass
Radiotelephone answered 4/10, 2019 at 7:52 Comment(0)
M
1

You can use set.difference:

   list(set.difference(                                                                                                                                              
       set(range(0, 32)),                                                                                                                                         
       set((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 20, 21))))

result:

Out[37]: [11, 14, 16, 17, 18, 19, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
Mechanician answered 24/12, 2023 at 16:49 Comment(0)
L
0
for i in range(100):
    if i == 50:
        continue
    dosomething
Lubricious answered 6/6, 2014 at 20:13 Comment(0)
T
0

It depends on what you want to do. For example you could stick in some conditionals like this in your comprehensions:

# get the squares of each number from 1 to 9, excluding 2
myList = [i**2 for i in range(10) if i != 2]
print(myList)

# --> [0, 1, 9, 16, 25, 36, 49, 64, 81]
Tuning answered 6/6, 2014 at 20:14 Comment(0)
S
0

This works for me;

example:

x = ['apple', 'orange', 'grape', 'lion', 'banana', 'watermelon', 'onion', 'cat',]

for xr in x:
    if xr in 'onion':
        print('onion is a vegetable')
        continue
    if (xr not in 'lion' and xr not in 'cat'):
        print(xr, 'is a fruit')

Output -->

apple is a fruit
orange is a fruit
grape is a fruit
banana is a fruit
watermelon is a fruit
onion is a vegetable
Sitzmark answered 19/4, 2021 at 10:52 Comment(0)
W
0

If you would like to skip over consecutive numbers where the initial number may be unknown, it is best to use a while loop.

# Loop through a range of numbers from 0 to 100 and skip over number 50 as well
# as the next 3 consecutive numbers (51, 52, 53). Additionally, skip over 11 to 14.

i = 0
initial_skip_num = (50, 11, )
while i < 100:
    if i in initial_skip_num:
        i += 4
    print(i)
    i += 1

Output:

0
1
...
9
10
15
16
...
48
49
54
55
...

This is helpful if the initial number to skip is unknown or multiple consecutive numbers need to be skipped

Wherein answered 2/3, 2023 at 10:39 Comment(0)
R
0

There is a set based approach you can use as part of the for-loop or list comprehension whatever, for example:

for x in set(range(100)) - {50}:
    print(x)
Rabon answered 25/2 at 12:46 Comment(0)
A
-1

what you could do, is put an if statement around everything inside the loop that you want kept away from the 50. e.g.

for i in range(0, len(list)):
    if i != 50:
        x= listRow(list, i)
        for j in range (#0 to len(list) not including x#)
Andy answered 6/11, 2016 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.