# libtmux._internal.sparse_array.SparseArray

- **Module:** libtmux._internal.sparse_array
- **Package:** libtmux
- **Language:** Python
- **Kind:** class
- **Source:** https://github.com/tmux-python/libtmux/blob/036c521c4b83ce6e434eb50afe2a0d08a6a05e46/src/libtmux/_internal/sparse_array.py#L29
- **Page:** https://libtmux.org/reference/py/libtmux-_internal-sparse_array-sparsearray/

Support non-sequential indexes while maintaining :class:`list`-like behavior.

A normal :class:`list` would raise :exc:`IndexError`.

There are no native sparse arrays in python that contain non-sequential indexes and
maintain list-like behavior. This is useful for handling libtmux options and hooks:

``command-alias[1] split-pane=split-window`` to
``{'command-alias[1]': {'split-pane=split-window'}}``

:class:`list` would lose indice info, and :class:`dict` would lose list-like
behavior.

## Example

Create a sparse array and add values at non-sequential indices:

```python
>>> from libtmux._internal.sparse_array import SparseArray
```

## Example

```python
>>> arr: SparseArray[str] = SparseArray()
>>> arr.add(0, "first hook command")
>>> arr.add(5, "fifth hook command")
>>> arr.add(2, "second hook command")
```

## Example

Access values by index (dict-style):

```python
>>> arr[0]
'first hook command'
>>> arr[5]
'fifth hook command'
```

## Example

Check index existence:

```python
>>> 0 in arr
True
>>> 3 in arr
False
```

## Example

Iterate values in sorted index order:

```python
>>> list(arr.iter_values())
['first hook command', 'second hook command', 'fifth hook command']
```

## Example

Convert to a list (values only, sorted by index):

```python
>>> arr.as_list()
['first hook command', 'second hook command', 'fifth hook command']
```

## Example

Append adds at max index + 1:

```python
>>> arr.append("appended command")
>>> arr[6]
'appended command'
```

## Example

Access raw indices:

```python
>>> sorted(arr.keys())
[0, 2, 5, 6]
```

## Members

- `add` (method) — Add a value at a specific index.
- `append` (method) — Append a value at the next available index (max + 1).
- `iter_values` (method) — Iterate over values in sorted index order.
- `as_list` (method) — Return values as a list in sorted index order.
