Daniel Cukier
Daniel Cukier

Reputation: 11942

How to merge lists into a list of tuples in Elixir?

What is the Elixir approach to merge two lists into a single list of tuples?

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]

# List of tuples from 'list1' and 'list2':
    
result = [{1,5}, {2,6}, {3,7}, {4,8}]

Each member of result is a tuple, whose first member is from list1 and the second is from list2.

Upvotes: 2

Views: 1142

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22360

You could consider using List.zip/1:

zip(list_of_lists)

     Specs

     zip([list()]) :: [tuple()]

Zips corresponding elements from each list in list_of_lists.

The zipping finishes as soon as any list terminates.

Example:

    iex(1)> list1 = [1, 2, 3, 4]
    [1, 2, 3, 4]
    iex(2)> list2 = [5, 6, 7, 8]
    [5, 6, 7, 8]
    iex(3)> result = List.zip([list1, list2])
    [{1, 5}, {2, 6}, {3, 7}, {4, 8}]

Upvotes: 1

Will Richardson
Will Richardson

Reputation: 7960

You can do this with Enum.zip/2:

Zips corresponding elements from a finite collection of enumerables into one list of tuples.

Enum.zip([[1, 2, 3], [:a, :b, :c], ["foo", "bar", "baz"]])
# [{1, :a, "foo"}, {2, :b, "bar"}, {3, :c, "baz"}]

Enum.zip([[1, 2, 3, 4, 5], [:a, :b, :c]])
# [{1, :a}, {2, :b}, {3, :c}]

Upvotes: 9

Related Questions