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 list
n = [11, 22, 33, 44, 55, 66]
#calculate length
l = length(n)
#print the length
IO.puts "The length of the list is #{l}"

Explanation

In the code above:

  • Line 2: We declare and initialize the list n with some numbers.
  • Line 5: We use the length() function to calculate the length of the list n and assign the returned length to variable l.
  • Line 8: We use IO.puts to print the length of the variable l.

Free Resources