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?
To start a numbered list, type 1, a period (.), a space, and some text. Word will automatically start a numbered list for you. Type* and a space before your text, and Word will make a bulleted list. To complete your list, press Enter until the bullets or numbering switch off.
By using Carl Gauss's clever formula, (n / 2)(first number + last number) = sum, where n is the number of integers, we learned how to add consecutive numbers quickly.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With