Alikhan
Alikhan

Reputation: 13

Python: How to range() multiple values from list or dictionary?

Im new to programming. Trying to range numbers - For example if i want to range more than one range, 1..10 20...30 50...100. Where i need to store them(list or dictionary) and how to use them one by one?

example = range(1,10)
exaple2 = range(20,30)

for b in example:
    print b

Upvotes: 1

Views: 6444

Answers (4)

Vlad Bezden
Vlad Bezden

Reputation: 89537

In Python3.x you can do:

output = [*range(1, 10), *range(20, 30)]

or using itertools.chain function:

from itertools import chain

data = [range(1, 10), range(20, 30)]
output = [*chain(*data)]

or using chain.from_iterable function

from itertools import chain

data = [range(1, 10), range(20, 30)]
output = [*chain.from_iterable(data)]

output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Upvotes: 0

gunzapper
gunzapper

Reputation: 457

or you can use yield from (python 3.5)

 def ranger():
     yield from range(1, 10)
     yield from range(20, 30)
     yield from range(50, 100)

 for x in ranger():
     print(x)         

Upvotes: 2

Gandhi
Gandhi

Reputation: 1

Range module helps you to get numbers between the given input.

Syntax:

range(x) - returns list starting from 0 to x-1

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

range(x,y) - returns list starting from x to y-1

>>> range(10,20)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>

range(x,y,stepsize) - returns list starting from x to y-1 with stepsize

>>> range(10,20,2)
[10, 12, 14, 16, 18]
>>>

Upvotes: 0

acdr
acdr

Reputation: 4716

The range function returns a list. If you want a list of multiple ranges, you need to concatenate these lists. For example:

range(1, 5) + range(11, 15)

returns [1, 2, 3, 4, 11, 12, 13, 14]

Upvotes: 1

Related Questions