Basics

Arrays in Python: Is the starting index 0 or 1?

funczun 2024. 11. 4. 11:04
Array

 An array is a kind of data structure that can store multiple elements. Numbers above the connected blanks refer to their respective indexes, and in all the programming languages we know commonly, the indexes of an array start at zero. For slicing, we exclude the values corresponding to the last index from the results. For better understanding, we will describe this as an "at least:below-rule" of indexing.

 

 The reason why it works with this "at least:below-rule" is that it is most effective. First, the "at least" structure including the start index intuitively expresses the start number to clarify the start of the range. Subsequently, the "below" structure that does not include the end index has the advantage of making it possible to intuitively find out the length of the sequence while it is inevitable to express the sequence continuity. The reason why the index of the array starts from 0 instead of 1 is that the length of the sequence can be known by looking at the end index.

 

Python: List

 An array in Python is basically a "list". A list is a basic data structure of Python that is not only dynamic, but also has the feature of being able to store a mixture of different data types. Therefore, Python's list cannot be said to be memory efficient. Because it is a dynamic arrangement, it is scaled as needed, and various data types are stored for flexibility, making the memory relationship complicated.

new_list = [1, 2, 3]
print(new_list[1:2])
[2]

 

Internal library: Array

 Of course, there are ways to prevent memory overhead. In Python, arrays can be created using array modules, which, unlike lists, have fixed data types and have good memory efficiency.

import array

new_array = array.array('i', [1, 2, 3])
print(new_array)
array('i', [1, 2, 3])

 

External library: NumPy array

 Furthermore, there is also an ndarray of the NumPy library, which is widely used for scientific computation. The NumPy array supports a multidimensional array and various mathematical operations. However, since it is not a built-in Python library, it must be installed separately.

import numpy as np

new_numpy_array = np.array([[1, 2, 3], [4, 5, 6]])
[[1 2 3]
 [4 5 6]]

pip install numpy

- Installing NumPy

import numpy as np
print(np.__version__)

- Varifying NumPy installation