1

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
Alikhan
  • 13
  • 1
  • 5
  • 4
    Check this question: http://stackoverflow.com/questions/13959510/python-list-initialization-using-multiple-range-statements – nucleon May 06 '16 at 11:33

4 Answers4

2

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)         
gunzapper
  • 457
  • 7
  • 19
1

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]

acdr
  • 4,538
  • 2
  • 19
  • 45
  • this doesn't work in Python3.x. TypeError: unsupported operand type(s) for +: 'range' and 'range' – Vlad Bezden Oct 13 '21 at 19:22
  • @VladBezden: you are correct. This answer was specifically for Python 2, not Python 3. The proper way is in the accepted answer by @gunzapper. If you want a less neat way that looks more similar to mine, you'll want to convert the two ranges to lists first: `list(range(1, 5)) + list(range(11, 15))` – acdr Oct 14 '21 at 13:24
0

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]
>>>
Gandhi
  • 1
  • 1
0

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]
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179