How to reverse a list in Elixir

What is a list in Elixir?

Lists in Elixir are effectively linked lists, which means that they are internally represented in pairs that contain the list’s head and tail.

What is the best way to reverse a list?

To implement the reversal of a list, we use the Enum and reverse() methods.

The Enum method

Enum is a method to work with enumerables. In this shot, we’ll concentrate on one of these enumerables, list.

The reverse() method

The reverse() method returns a list that has been turned around.

Syntax of reverse()

reverse(enumerable)

Parameters

The reverse() method takes an enumerable, like a list, as a parameter.

How to use Enum and reverse() together

We can use a dot notation to chain the methods together and pass the list as an argument in the reverse() method.

Let’s look at an example:

list = [1, 2, 3]
reverse = Enum.reverse(list)
IO.inspect reverse, label: "The reverse list is"
#⇒ The list is: [1, 2, 3]

Code explanation

  • Line 1: We create a variable called list and store numbers in it.

  • Line 2: We use Enum.reverse(list) to reverse the list and save it in the reverse variable. The list there is enumerable, as discussed above.

  • Line 3: We use IO.inspect to print the result of the reverse variable.

Output

The output is a list in its reversed state.

Free Resources