Menu

An array is a data structure that holds several values together under a single identifier. Each value held in the array is called an element, and each element is located by an index that gives its position.

Indexing is zero-based: the first element sits at index 0, the second at index 1, and so on. The index counts how far an element is from the start, so the front element takes no steps and is numbered 0. An array of five elements therefore uses indexes 0 to 4.

Elements and indexes

The program below stores the lap times, in seconds, that a runner recorded. All five values are integers, held together under the identifier lap_times.

# a one-dimensional array of five integers
lap_times = [62, 58, 71, 65, 59]
print(lap_times[0])
print(lap_times[3])

Output:

62
65
Index01234
Element6258716559

The identifier names the whole collection, while an index in square brackets picks out one element; index 2 of lap_times holds 71.

One-dimensional arrays in Python

A one-dimensional array stores a single sequence of values, so one index is enough to locate any element. In Python you write one as a list: the values go inside square brackets, separated by commas, as in the lap times program.

An array holds elements of one data type, so you build an array of integers or strings, not a mixture. Keeping to one type means the same operation makes sense on every element: you can add up every number in an array of integers. Python will not actually stop you mixing types in a list, but the array you need to describe holds values of one type.

Arrays are widely used in high-level languages because programs work with collections of related values, such as lap times, players or prices. In Python the list is the array structure, so the square-bracket syntax creates and uses one.

Practise this