-1

If I have two integer (start, end),

for example,

start, end = 3,8 

then I want to create a list that includes all integers from 3 to 8 (also includes 3 and 8)

[3,4,5,6,7,8]

How can I get that?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Jign
  • 149
  • 1
  • 1
  • 10

2 Answers2

6

Python 3: use range as the generator, and list to complete:

list(range(start, end+1))

For Python 2, take note of range vs xrange and that you'd need a call to list if you go the route of xrange, which acts the same as range in Python 3.

Community
  • 1
  • 1
Celeo
  • 5,583
  • 8
  • 39
  • 41
0

You can use built-in range function for it:

In python 2.x

>>> start, end = 3, 8
>>> range(start, end+1)
[3, 4, 5, 6, 7, 8]

In python 3.x you have to call list function on range to get list as range by itself returns generator object.

In [1]: start, end = 3, 8
In [2]: range(start, end+1)
Out[2]: range(3, 9)
In [3]: list(range(start, end+1))
Out[3]: [3, 4, 5, 6, 7, 8]
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43