Files
opentf/website/docs/language/functions/element.mdx
Martin Atkins 68fbe8d8d7 website: "element" function supports negative indices
We got this new functionality from an upgrade of the upstream cty library,
but we didn't update the docs to mention it.

The examples in this doc were also evidently generated with a much older
version of OpenTofu's predecessor, because the illustrated output was not
shown as a quoted string. The example output now matches how the current
version of "tofu console" would describe these results.

Signed-off-by: Martin Atkins <mart@degeneration.co.uk>
2025-10-28 15:11:26 -07:00

57 lines
1.4 KiB
Plaintext

---
sidebar_label: element
description: The element function retrieves a single element from a list.
---
# `element` Function
`element` retrieves a single element from a list.
```hcl
element(list, index)
```
The index is zero-based. This function produces an error if used with an
empty list.
Use the built-in index syntax `list[index]` in most cases. Use this function
only for the special additional "wrap-around" behavior described below.
## Examples
If the given index is less than the length of the given list then this
function is equivalent to the normal index operator:
```
> element(["a", "b", "c"], 1)
"b"
> ["a", "b", "c"][1]
"b"
```
However, this function exists mainly for the special way it treats indices that
are out of range for the list's length, which would therefore cause an error
if used with the normal index operator.
If the given index is greater than the length of the list then the index is
"wrapped around" by taking the index modulo the length of the list:
```
> element(["a", "b", "c"], 3)
"a"
```
This wrap-around behavior also works in the negative direction, so you can
use negative indices to select elements relative to the end of the given
list:
```
> element(["a", "b", "c"], -1)
"c"
```
## Related Functions
* [`index`](../../language/functions/index_function.mdx) finds the index for a particular element value.
* [`lookup`](../../language/functions/lookup.mdx) retrieves a value from a _map_ given its _key_.