2018-05-12 18:39:29 +02:00
|
|
|
---
|
2021-12-15 03:41:17 +01:00
|
|
|
page_title: element - Functions - Configuration Language
|
|
|
|
description: The element function retrieves a single element from a list.
|
2018-05-12 18:39:29 +02:00
|
|
|
---
|
|
|
|
|
|
|
|
# `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
|
2020-10-31 01:42:40 +01:00
|
|
|
empty list. The index must be a non-negative integer.
|
2018-05-12 18:39:29 +02:00
|
|
|
|
|
|
|
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
|
|
|
|
```
|
|
|
|
|
2021-12-15 03:41:17 +01:00
|
|
|
To get the last element from the list use [`length`](/language/functions/length) to find
|
2020-10-22 20:03:27 +02:00
|
|
|
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
|
|
|
|
```
|
|
|
|
|
2018-05-12 18:39:29 +02:00
|
|
|
## Related Functions
|
|
|
|
|
2021-12-15 03:41:17 +01:00
|
|
|
* [`index`](/language/functions/index_function) finds the index for a particular element value.
|
|
|
|
* [`lookup`](/language/functions/lookup) retrieves a value from a _map_ given its _key_.
|