2

This is 100% a dumb question but I couldn't find the answer. Would i be able to do a for loop between two different intervals?

Take for example:

array = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,5) and range(7,9):
    print(array[i])

and it would output: 1,2,3,4,5,8,9

Edit: As Adam.Er8 pointed out, itertools.chain, would be the cleaner solutions.

Another solution I found while experimenting was without the itertools would be:

array = [1,2,3,4,5,6,7,8,9,10]
needrange = [[1,3],[5,7],[8,9]]
for j in range(0,len(needrange)):
    for i in range(needrange[j][0],needrange[j][1]):
        print(array[i])

This solution isn't clean but it does do the job if you aren't looking to import.

Credit to cs95 from a similar question, who wrote:

ranges = [range(2, 5), range(3, 7), ...]
flat = list(chain.from_iterable(ranges))

Notes found while writing this response):

I'm pretty sure range(n,m) from cs95 answer just returns a list as well, whereas I just created a list initially. So very similar

The function from itertools,looks very similar logic wise, but I just found my solution easier to read.

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • 1
    @jerin That's right. *"The expression `x and y` first evaluates x; if `x` is false, its value is returned; otherwise, `y` is evaluated and the resulting value is returned."* https://docs.python.org/3/reference/expressions.html#boolean-operations – slothrop Jun 22 '23 at 08:48

4 Answers4

3

You can use itertools.chain(range(0,5), range(7,9))

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
1

Not pretty, but you can do

for i in list(range(0,5)) + list(range(7,9)):
    print(array[i])

You can add lists together; just not ranges.

Well, that's not entirely true, using itertools.chain:

from itertools import chain
for i in chain(range(0,5), range(7,9)):
    print(array[i])

It doesn't really add them together; it just "chains" any iterable, including a range object.

9769953
  • 10,344
  • 3
  • 26
  • 37
1
array = [1,2,3,4,5,6,7,8,9,10]
for i in [*range(0,5), *range(7,9)]:
    print(array[i])
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
0

I'm assuming you mean "how do I create an union between 2 different ranges?", in which case:

for i in list(range(0, 5)) + list(range(7, 9)):
    # ...

Although, a warning: Doing it this way will expand the range into a list, putting every element in it in its own entry. Doing this with a large range may cause memory issues

0x150
  • 589
  • 2
  • 11