Files
opentf/website/docs/language/functions/element.mdx
2024-04-24 13:24:30 +02:00

48 lines
1.2 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. The index must be a non-negative integer.
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
```
> element(["a", "b", "c"], 1)
b
```
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
```
To get the last element from the list use [`length`](../../language/functions/length.mdx) to find
the size of the list (minus 1 as the list is zero-based) and then pick the
last element:
```
> element(["a", "b", "c"], length(["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_.