An array in Python is a collection of elements where each element is being assigned an index number and are consisting of the same data type. The elements can be picked out and used using the index.
We have previously seen how we can store values in variables, for example:
var = 10
The variable var, of type integer, is assigned the value 10.
But what if we have a hundred values that we want to save at the same time? A thousand values? One million values? In order to handle a very large amount of data at the same time, we use arrays (also called fields, or in other programming languages; lists). This allows us to save multiple values in one variable.
Let’s start by taking a look at the so called one-dimensional array. We can think of an array as a collection or block of values. For example, we can create an array of integers:
my_list = [5, 2, 8, 9, 3]
my_list now contains 5 values.
You can print the entire list at once:
and get the result
[5, 2, 8, 9, 3]
That is, instead of creating separate variables for each value, we can instead create an array that contains all values at the same time.
When we develop our programs we will often handle collections of objects of the same type and then an array is a very useful tool to be able to structure and group the objects together.
As we have seen before, a variable can be seen as an object or a box that contains a data type and which also can have an assigned value. The image to the right illustrates a variable that has the name var and the value 23.
In a similar way, we can now think of an Array as a box that has several boxes inside. We can access each box using its index and in that way use it, read the value and also edit that value. The image to the right illustrates how you might imagine an array looks, to make it easier to understand what it is. In the image there is an array with the name field that has a set of different values.
Now that we have got a basic understanding of what an array in python is, we are now going to go on and see how we actually can create and use the array. Then we will also look at a few different uses and examples. We will also look at some simple errors that are easy to occur if you are not observant.