Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 990
yezi3 Avatar asked Apr 10 '15 09:04

yezi3


People also ask

How do I make a list of numbers?

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.

What is the fastest way to add consecutive numbers?

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.


1 Answers

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.

like image 189
thefourtheye Avatar answered Sep 20 '22 04:09

thefourtheye