Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating an ascending list of numbers of arbitrary length in python

Tags:

python

list

range

Is there a function I can call that returns a list of ascending numbers? I.e., function(10) would return [0,1,2,3,4,5,6,7,8,9]?

like image 222
Patrick Avatar asked Nov 05 '10 17:11

Patrick


People also ask

How do you create an ascending list in Python?

Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.

How do you generate a list of sequential numbers in Python?

Python comes with a direct function range() which creates a sequence of numbers from start to stop values and print each item in the sequence. We use range() with r1 and r2 and then convert the sequence into list.

How do you make a list of integers in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.).


3 Answers

You want range().

like image 150
Ignacio Vazquez-Abrams Avatar answered Oct 14 '22 04:10

Ignacio Vazquez-Abrams


range(10) is built in.

like image 37
Ned Batchelder Avatar answered Oct 14 '22 05:10

Ned Batchelder


If you want an iterator that gives you a series of indeterminate length, there is itertools.count(). Here I am iterating with range() so there is a limit to the loop.

>>> import itertools
>>> for x, y in zip(range(10), itertools.count()):
...     print x, y
... 
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

Later: also, range() returns an iterator, not a list, in python 3.x. in that case, you want list(range(10)).

like image 26
hughdbrown Avatar answered Oct 14 '22 05:10

hughdbrown