distinct removes repeated values from a list. Comparing its length with the original list’s length also tells you whether the list had duplicates.
Syntax
distinct(<LIST>)
<LIST>: the list to clean up. The docs say the first occurrence of each value is kept, in the original order.
The function is described in distinct Function (opens in a new tab) in the OpenTofu® docs.
Prerequisites
- OpenTofu installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
Step 1: Try It in tofu console
Open a terminal in any empty folder and start tofu console, which evaluates expressions as you type them:
tofu console
Type each expression to see the result:
> distinct(["tea", "cake", "tea", "jam", "cake"])
tolist([
"tea",
"cake",
"jam",
])
> distinct([3, 1, 3, 2, 1])
tolist([
3,
1,
2,
])
> exit
Clean Up
Type exit to leave the console. The example creates nothing, so there’s nothing else to remove.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Expecting the result to be sorted | It keeps the original order of the first occurrences. | Sort it separately if you need an order. |
Expecting "Tea" and "tea" to count as the same | They’re different values, so both stay. | Make them the same case first, for example with lower. |
FAQ
How do I check that a list has no duplicates?
Compare lengths: when length(distinct(var.names)) == length(var.names) is true, every name is unique.
Why does the result say tolist?
The console shows that the result is a list; its values are the ones you see.
Conclusion
distinct(<LIST>) returns the list with each value once, in the order they first appear.
Additional Resources
OpenTofu® is a registered trademark of LF Projects, LLC. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by the OpenTofu project.
0 comments