How to create a list of numbers in python ?

Published: March 09, 2018

DMCA.com Protection Status

Examples of how to create a list of numbers in python using list comprehensions or built-in functions list():

Create a list of integers

To create a list of integers between 0 and N, a solution is to use the range(N) function:

>>> l = [i for i in range(10)]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To create a list of integers between N and M (with M>N), the function range() can still be used:

>>> l = [i for i in range(25,35)]
>>> l
[25, 26, 27, 28, 29, 30, 31, 32, 33, 34]
>>> l = list(range(25,35))
>>> l
[25, 26, 27, 28, 29, 30, 31, 32, 33, 34]

Create a list of floats using arange

To create a list of floats between (N,M) with a given step, a solution is to use the numpy function called arange:

>>> import numpy as np
>>> l = [i for i in np.arange(2,8,0.5)]
>>> l
[2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5]
>>> l = list(np.arange(2,8,0.5))
>>> l
[2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5]

Create a list of floats using linspace

To create a list of floats between (N,M) with a given number of elementsa solution is to use the numpy function linspace:

>>> import numpy as np
>>> l = [i for i in np.linspace(12,16,8)]
>>> l
[12.0, 12.571428571428571, 13.142857142857142, 13.714285714285714, 14.285714285714285, 14.857142857142858, 15.428571428571429, 16.0]
>>> l = list(np.linspace(12,16,8))
>>> l
[12.0, 12.571428571428571, 13.142857142857142, 13.714285714285714, 14.285714285714285, 14.857142857142858, 15.428571428571429, 16.0]

Create a list of random integers

The python function randint can be used to generate a random integer in a chosen interval [a,b]:

>>> import random
>>> random.randint(0,10)
7
>>> random.randint(0,10)
0

A list of random numbers can be then created using python list comprehension approach:

>>> l = [random.randint(0,10) for i in range(5)]
>>> l
[4, 9, 8, 4, 5]

Another solution is to use randrange function (except that can specify a step if you need):

>>> l = [random.randrange(0,10) for i in range(5)]
>>> l
[1, 7, 4, 3, 1]
>>> l = [random.randrange(0,10,2) for i in range(5)]
>>> l
[2, 4, 4, 6, 0]

A third solution is to create a list of random numbers with no repetition, is to use random.sample function

>>> l = random.sample(range(1,100), 10)
>>> l
[89, 56, 87, 51, 46, 25, 52, 44, 10, 32]

References