4.2.1.1–4.2.1.2 - Data structures and multidimensional arrays (Python)

4.2.1.1–4.2.1.2 - Data structures and multidimensional arrays (Python)

Choose structures that match a problem, represent vectors and matrices with indexed collections, and write Python solutions that visit each required element safely.

Choosing a data structure

A data structure organises related data so that the operations a program needs are clear and practical.

Data structure

A way of organising and storing data, together with the relationships that allow it to be accessed and changed.

A single variable can hold today's attendance. A collection is needed to hold attendance for every class. Choosing a structure starts with the questions the program must answer: is order significant, will records be found by position or key, and how will items be added or removed? An indexed collection suits daily temperatures in chronological order. A dictionary suits retrieving a pupil's details by a unique pupil ID. A queue suits requests served in arrival order. These choices affect the simplicity and cost of later operations.

An array is an indexed collection whose elements share a data type. Many languages give an array a fixed length. Python lists are a useful equivalent for these problems, but Python lists can grow and can contain mixed types. When using a list as a numerical array, deliberately keep its elements of the intended type and decide whether the logical length is fixed. A list is not automatically a queue, stack or matrix merely because it stores several values; the program's organisation and permitted operations give it that role.

Vectors and matrices as arrays

The number of indices needed to select one element determines the dimension of an array.

A one-dimensional array uses one index and can represent a vector: temperatures = [18.0, 19.5, 17.0]. Python indexing starts at zero, so temperatures[1] is 19.5. A two-dimensional array can represent a matrix. Here rows are days and columns are rooms:

Python
readings = [[18, 20, 19],
            [17, 21, 18]]
print(readings[1][2])  # day index 1, room index 2: 18

The first index selects a row; the second selects an element in that row. This matrix has two rows and three columns. More generally, an n-dimensional array selects each element by a tuple of n integers, an ordered list of indices. In a three-dimensional collection, (week, day, room) identifies one reading. Decide and document the index meaning before writing loops.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account