Fix Python – How do I create a list with numbers between two values?

Question

Asked By – lorde

How do I create an ascending list between two values? For example, a list between 11 and 16:

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

Now we will see solution for issue: How do I create a list with numbers between two values?


Answer

Use range. In Python 2, it returns a list directly:

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

In Python 3, range is an iterator. To convert it to a list:

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

Note: The second number in range(start, stop) is exclusive. So, stop = 16+1 = 17.


To increment by steps of 0.5, consider using 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]

See: How do I use a decimal step value for range()?

This question is answered By – Jared

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0