One-dimensional arrays¶
Content summary
This lesson covers the general concepts of arrays, with a focus on one-dimensional arrays.
Overview of arrays¶
Problem statement¶
When managing the computer science grades for a class of 30 students, declaring 30 separate variables feels pretty impractical. Just look at how clunky this declaration code gets:
(This introductory problem is similar to the list data structure` lesson from grade 10.)
If there were even more students — say, 500 across the whole grade — declaring each variable one by one would be completely impossible.
Fortunately, programming languages provide data structures that make handling grade lists like this much easier, and one of the key ones is the array.
Concept¶
In most programming languages, an array is a data structure used to store and process a collection of elements, where:
- The elements are stored consecutively in memory.
- All elements have the same data type (e.g., all integers, all floating-point numbers, etc.).
- The number of elements is finite and usually fixed in advance.
-
Each element is accessed using one or more indices, depending on the number of dimensions of the array. For example:
- A one-dimensional array uses 1 index.
- A two-dimensional array uses 2 indices.
- A three-dimensional array uses 3 indices.
Arrays are commonly used to solve problems involving multiple related values of the same type. In practice, almost every real-world programming problem involves at least one form of array.
Examples:
- Computer science grades of students in a class.
- Time measurements recorded during physics experiments.
More details about arrays
- Conceptually, array elements are stored consecutively in memory. However, in practice:
- Static and dynamic arrays still store elements next to each other.
-
But in other similar data structures (like linked lists), elements may be scattered across memory.
-
In traditional programming languages like C or Java, all elements in an array must be of the same data type.
In contrast, modern languages like JavaScript, Ruby, or Python allow arrays (or similar structures) to hold elements of different data types.
Classification¶
Arrays are classified by dimension into the following types:
- One-dimensional arrays
- Two-dimensional arrays
- Multi-dimensional arrays
This lesson focuses only on one-dimensional arrays.
One-dimensional arrays¶
Concept¶
A one-dimensional array is the most basic data structure used to store elements of the same data type, arranged in a single row or a single column.
Each element is identified by an index, which usually starts from 0.
The image below illustrates a one-dimensional array A.
Real-life examples of a one-dimensional array:
- A row of classrooms
- A row of seats in a movie theater
One-dimensional arrays are useful when working with:
- A sequence of numbers
- A single row or column in a table
One-dimensional arrays in Python¶
In Python, arrays can be represented using the list data structure or the array module.
However, since list was already covered in the grade 10 curriculum (1), arrays in grade 11 will no longer use list. Instead, these lessons will use the open-source library numpy.
- and
arraystill has some limitations
Using numpy will focus only on basic operations, and it does not change the main goal: teaching and learning algorithmic ideas.
The numpy library
Key advantages of the numpy library include:
- Contiguous storage and uniform data types, enabling O(1) access time — very fast.
- Vectorized operations: process entire arrays at once, making it tens to hundreds of times faster than
forloops onlist. - Built-in math functions for statistics, linear algebra, and more.
- Widely used worldwide in data science, AI, physics, and engineering.
Installing the numpy library¶
Before using it, you need to install the numpy library using the pip command.
For Visual Studio Code:
- Open the Terminal (or PowerShell, or Command Prompt) using the shortcut Ctrl+` (the key to the left of 1).
Or go to the menu: View > Terminal.
- In the Terminal window, type the following command:
For Google Colab
-
In any code cell, enter this command:
-
Run the cell. If you see output similar to this, installation was successful:
Now you can start writing code in another cell.
Importing the library¶
At the beginning of your program, import the numpy library using the import statement. By convention, we use np as the short name for numpy.
Initialization¶
To create a one-dimensional array, we use the array() function from numpy.
The elements are listed inside square brackets [ ] and separated by commas ,.
Example:
Line 5 creates a one-dimensional array A by listing its elements.
-
f'...'is Python's f-string (formatted string literal) syntax, used to display the value of the variableA.Inside an f-string, anything within
{}is replaced with its actual value.
Running the code above gives the following output:
To create a one-dimensional array with all elements having the same value, we use the full() function from numpy.
Example:
Line 11 creates an array zeros with eight elements, all equal to 0.
Running the code above gives the following output:
Accessing elements¶
Each element is accessed using its index, placed inside square brackets [ ].
The first element has index 0, and the last element has index len(array) - 1.
Example:
Lines 8 and 11 print the first and last elements of array A.
Running the code above gives the following output:
Example:
Line 14 causes an error because array A does not have an element with index 12.
Running the code above produces an error message similar to the following:
IndexError Traceback (most recent call last)
/tmp/ipython-input-2733226203.py in <cell line: 0>()
12
13 # Chương trình báo lỗi vì không có chỉ số 12 trong mảng A
---> 14 print(f'Phần tử có chỉ số 12: {A[12]}')
IndexError: index 12 is out of bounds for axis 0 with size 12
Traversing the array¶
In many problems, array elements are processed in a similar way. That’s why we often use a loop to traverse the array.
Example:
Lines 8 and 9 loop through the array to print each element from start to end — one element per line.
Running the code above gives the following output:
A[0] = 1
A[1] = 7
A[2] = 4
A[3] = 0
A[4] = 9
A[5] = 4
A[6] = 8
A[7] = 8
A[8] = 2
A[10] = 5
A[11] = 5
Example:
Lines 12 and 13 traverse the array to print the elements from the end back to the start, all on thesame line.
-
The
endparameter of theprint()function defaults to'\n', which means a new line after each printed element.Setting
end=' 'prints a space after each element instead.
Running the code above gives the following output:
Source code¶
The complete code is available at:
Summary mindmap¶
Some English words¶
| Vietnamese | Tiếng Anh |
|---|---|
| chỉ số (của phần tử) | index |
| đánh chỉ số từ 0 | zero-based indexing |
| giá trị (của phần tử) | value |
| mảng một chiều | one-dimensional array |
| phần tử | element, item |
| vị trí | position |