Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two for loops

Lets say i'm trying to print 0 to 25 and 75 to 100. Right now I have:

for x in range(0, 26):
    print(x)
for x in range(75, 101):
    print(x)

Is there any way to combine these into a single for loop that lead to:

print(x)

?

Something along the lines of:

for x in range(0, 26) and range(75, 101):
    print(x)
like image 214
Funjando Avatar asked Feb 07 '23 20:02

Funjando


1 Answers

You need the 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.

from itertools import chain

for x in chain(range(0, 26), range(75, 101)):
    print(x)

Works for both Python 2 and 3.

like image 177
alecxe Avatar answered Feb 20 '23 22:02

alecxe