Elixir Lists

From Elixir Wiki
Jump to navigation Jump to search

Elixir Lists[edit]

The Elixir programming language provides a powerful data structure known as a list. In Elixir, a list is an ordered collection of elements. Lists can contain elements of any data type, including numbers, strings, atoms, and even other lists. Lists in Elixir are immutable, which means they cannot be modified once created. Instead, operations on lists return new lists.

Creating Lists[edit]

To create a list in Elixir, we can use square brackets `[ ]` and separate the elements with commas.

```elixir my_list = [1, 2, 3, 4, 5] ```

We can also use the `++` operator to concatenate two lists together.

```elixir list1 = [1, 2, 3] list2 = [4, 5, 6] combined_list = list1 ++ list2 ```

Accessing List Elements[edit]

In Elixir, we can access individual elements in a list using the square bracket notation.

```elixir my_list = [1, 2, 3, 4, 5] second_element = my_list[1] ```

We can also use pattern matching to extract elements from a list.

```elixir [first_element | rest_of_list] = my_list ```

This will bind the variable `first_element` to the first element of the list and `rest_of_list` to the remaining elements.

List Operations[edit]

Elixir provides a wide range of functions to manipulate lists:

- `List.length/1` - Returns the length of a list. - `List.first/1` - Returns the first element of a list. - `List.last/1` - Returns the last element of a list. - `List.flatten/1` - Flattens a nested list into a single level list. - `List.reverse/1` - Reverses the order of elements in a list. - `List.delete/2` - Deletes the first occurrence of an element in a list. - `List.duplicate/2` - Creates a new list with a given element duplicated a certain number of times.

List Comprehensions[edit]

Elixir supports list comprehensions, a powerful syntax for transforming and filtering lists.

```elixir squares = for x <- [1, 2, 3, 4, 5], do: x * x ```

This will produce a new list `squares` containing the squares of the elements in the original list.

Conclusion[edit]

Lists are a fundamental data structure in Elixir and understanding their operations and usage is crucial for writing efficient and effective Elixir code. By utilizing the operations and syntax described in this article, developers can manipulate and transform lists to suit their specific needs.