# Zero-based indexing

In math we use 1-based indexing, but in many programming languages including Python, we use 0-based indexing.

For example, a three dimensional vector $\vec{v} \in \mathbb{R}^3$ are denoted as $(v_1,v_2,v_3)$ in components form.

In Python a vector `vec` can be denoted as a list (or a Matrix), and its three components will be `vec[0]`, `vec[1]`, and `vec[2]`. The variable we to index the components is assumed to start at zero, not one.


```python
from sympy import Matrix, symbols
a, b, c = symbols('a b c')

vec = Matrix([a,b,c])
vec
```




$\displaystyle \left[\begin{matrix}a\\b\\c\end{matrix}\right]$




```python
vec[0]
```




$\displaystyle a$




```python
vec[1]
```




$\displaystyle b$




```python
vec[2]
```




$\displaystyle c$




```python
# trying to access vec[3] leads to an error, 
# since a 3 in 0-based indexing is accessing a fourth component which doesn't exist
vec[3]
```

## Ranges


```python
# a list of five numbers
list(range(0,5))
# Note the second argument of the function range specifies
#      the first number not to be included in the range...
```




    [0, 1, 2, 3, 4]




```python

```

## SymPy shorthand for ranges


```python
# consider a 2x3 matrix
A = Matrix([
        [1,2,3],
        [4,5,6]])
A
```




$\displaystyle \left[\begin{matrix}1 & 2 & 3\\4 & 5 & 6\end{matrix}\right]$




```python
# can access individual entry on row i, col j using A[i-1,j-1]
print('top left =',    A[0,0], '    top right =', A[0,2])
print('bottom left =', A[1,0], ' bottom right =', A[1,2])
```

    top left = 1     top right = 3
    bottom left = 4  bottom right = 6



```python
# can access entire colum j using A[:,j-1]
A[:,0]
```




$\displaystyle \left[\begin{matrix}1\\4\end{matrix}\right]$




```python
# can access entire row i using A[i-1,:]
A[0,:]
```




$\displaystyle \left[\begin{matrix}1 & 2 & 3\end{matrix}\right]$




```python
# can access left 2x2 submatrix using i:j shorhand range notation
A[0:2,0:2]
```




$\displaystyle \left[\begin{matrix}1 & 2\\4 & 5\end{matrix}\right]$




```python
# the above notation is MATLAB-like syntax sugar that translates to
A[range(0,2),range(0,2)]
```




$\displaystyle \left[\begin{matrix}1 & 2\\4 & 5\end{matrix}\right]$




```python

```


```python

```

b56fecb50613fa9b44fc572fe764f702cee32cd0
ipynb
Jupyter Notebook
extra/python_basics_zero_based_indexing.ipynb
minireference/noBSLAnotebooks
3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4
MIT
2016-04-20T13:56:02.000Z
2022-03-30T08:55:08.000Z
extra/python_basics_zero_based_indexing.ipynb
minireference/noBSLAnotebooks
3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4
MIT
2021-07-01T17:00:38.000Z
2021-07-01T19:34:09.000Z
extra/python_basics_zero_based_indexing.ipynb
minireference/noBSLAnotebooks
3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4
MIT
2017-02-04T05:22:23.000Z
2021-12-28T00:06:50.000Z
Qwen/Qwen-72B
1. YES
2. YES