Python - Create list with numbers between 2 values?

lorde picture lorde · Aug 16, 2013 · Viewed 1.2M times · Source

How would I create a list with values between two values I put in? For example, the following list is generated for values from 11 to 16:

list = [11, 12, 13, 14, 15, 16]

Answer

Jared picture Jared · Aug 16, 2013

Use range. In Python 2.x it returns a list so all you need is:

>>> range(11, 17)
[11, 12, 13, 14, 15, 16]

In Python 3.x range is a iterator. So, you need to convert it to a list:

>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]

Note: The second number is exclusive. So, here it needs to be 16+1 = 17

EDIT:

To respond to the question about incrementing by 0.5, the easiest option would probably be to use numpy's arange() and .tolist():

>>> import numpy as np
>>> np.arange(11, 17, 0.5).tolist()

[11.0, 11.5, 12.0, 12.5, 13.0, 13.5,
 14.0, 14.5, 15.0, 15.5, 16.0, 16.5]