| --- | |
| 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_. |