How can I generate a list of consecutive numbers?
Say if you had a number input 8
in python and you wanted to generate a list of consecutive numbers up to 8
like
[0, 1, 2, 3, 4, 5, 6, 7, 8]
How could you do this?
Solution 1:
In Python 3, you can use the builtin range
function like this
>>> list(range(9))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Note 1: Python 3.x's range
function, returns a range
object. If you want a list you need to explicitly convert that to a list, with the list
function like I have shown in the answer.
Note 2: We pass number 9 to range
function because, range
function will generate numbers till the given number but not including the number. So, we give the actual number + 1.
Note 3: There is a small difference in functionality of range
in Python 2 and 3. You can read more about that in this answer.
Solution 2:
Using Python's built in range function:
Python 2
input = 8
output = range(input + 1)
print output
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Python 3
input = 8
output = list(range(input + 1))
print(output)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Solution 3:
Here is a way to generate n consecutive numbers in equal intervals between them starting from 0 to 100 using numpy:
import numpy as np
myList = np.linspace(0, 100, n)
Solution 4:
Just to give you another example, although range(value) is by far the best way to do this, this might help you later on something else.
list = []
calc = 0
while int(calc) < 9:
list.append(calc)
calc = int(calc) + 1
print list
[0, 1, 2, 3, 4, 5, 6, 7, 8]