gdogg371
gdogg371

Reputation: 4122

Iterate Two Ranges In For Loop

I have a couple of simple loops like so:

for i in range (30, 52):

    #do some stuff here

for i in range (1, 18):

    #do some more stuff

What I would like to is condense this into one loop using syntax of the order:

for i in range((30, 52), (1, 18):

    #do some stuff

I realise that syntax will not work, but that is the basic concept of what I need. I've seen people using zip to iterate two ranges simultaneously, but this is not what I need.

Any ideas?

Upvotes: 20

Views: 45038

Answers (4)

Renat Abdrakhmanov
Renat Abdrakhmanov

Reputation: 25

for i, j in zip(range(30, 52), range(1, 18)):
    print(i, j)

Upvotes: 0

utdemir
utdemir

Reputation: 27216

From https://docs.python.org/2/library/itertools.html#itertools.chain :

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

Example:

import itertools as it
for i in it.chain(range(30, 52), range(1, 18)):
    print(i)

for python 3

you can loop into the two ranges together

Example:

import itertools as it
for i, x in it.zip_longest(range(30, 52), range(1, 18)):
    print(i, x)

Upvotes: 32

Oleg K
Oleg K

Reputation: 111

You can convert the two iterators for your ranges to lists and then combine them with an addition:

for i in list(range(30, 52)) + list(range(1, 18)):
    # something

Upvotes: 11

Alexander  Kobotov
Alexander Kobotov

Reputation: 35

for i in range(30, 52) + range(1, 18):
    #something

Upvotes: -1

Related Questions