Funjando
Funjando

Reputation: 45

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)

Upvotes: 4

Views: 3688

Answers (4)

MaThMaX
MaThMaX

Reputation: 2015

Using List Comprehension:

[i for j in (range(0, 26), range(75, 101)) for i in j]

Upvotes: 1

Jeremy
Jeremy

Reputation: 828

Here's a way to do it with list comprehension and a single line, if you don't want to import anything. You basically add all the numbers to a list, then print the list as a long string with newline characters after each number.

print("\n".join([str(x) for x in range(0,101) if x < 26 or x > 74]))

Upvotes: 0

Bryce Drew
Bryce Drew

Reputation: 6729

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

You can concatenate two lists by adding them.

Upvotes: 0

alecxe
alecxe

Reputation: 473833

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.

Upvotes: 7

Related Questions