How to get the length of a list in Elixir
Overview
In this shot, we will learn how to use the length() function to calculate the length of a list in Elixir.
A list is a heterogeneous collection of items in Elixir.
- A list is specified between square brackets
[]and separated with a comma,. - Under the hood, lists in elixir are linked lists.
Syntax
length(list)
Parameters
This method accepts a list as a parameter.
Return value
The length() function returns the length of the list that is passed as a parameter.
Example
In the example below, we will calculate the length of the list of numbers.
Code
# declare and initialize the listn = [11, 22, 33, 44, 55, 66]#calculate lengthl = length(n)#print the lengthIO.puts "The length of the list is #{l}"
Explanation
In the code above:
- Line 2: We declare and initialize the list
nwith some numbers. - Line 5: We use the
length()function to calculate the length of the listnand assign the returned length to variablel. - Line 8: We use
IO.putsto print the length of the variablel.