Skip to main content

How to Create an Array of Numbers 0 to N in Python

Creating arrays is a fundamental part of coding. In this blog post, we’ll show you how to create an array of numbers 0 to N in Python.

range()

The first step is to create the array. We’ll do this by using the range() function. The range() function takes two parameters: the start and the stop. The start is the first number in the array, and the stop is the last number in the array. We want our array to include all numbers from 0 up to N, so we’ll set the start parameter to 0 and the stop parameter to N+1. Here’s what that looks like in code:

integer_list = list(range(0, 10))
print(integer_list)
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Now that we have our array, let’s take a look at a few ways we can use it in our code. 

array

In Python, an array is a list. If you want to use an array, you need to import the array module. The array module is a part of the standard library, so you don’t need to install anything to use it.

Once you’ve imported the array module, you can create an array by using the array() function. The array() function takes two parameters: the data type and the list of numbers. We want our array to contain integers, so we’ll set the data type to int. We’ll also init the list of numbers to our array variable.

import array
import itertools

integer_array = array.array("i", itertools.repeat(0, 10))

numpy

numpy is a third-party module that you can install with pip. Numpy is not part of the standard library, so you need to install it before you can use it.

Once you’ve installed numpy, you can create an array by using the np.arange() function.

import numpy

integer_array = numpy.arange(0, 50)
print(integer_array)

By continuing to use the site, you agree to the use of cookies.