24

Given one list with one tuple:

[{4,1,144}]

How to extract the first element of the tuple inside the list:

element(1,lists:nth(1,L))

Do you have a simpler solution?

3 Answers 3

36

Try this:

1> A = [{3,1,1444}].
[{3,1,1444}]
2> [{X, _, _}] = A.
[{3,1,1444}]
3> X.
3
4> 
3
  • 1
    I like this solution very simple ;-)
    – Bertaud
    Commented Jan 27, 2011 at 22:29
  • 4
    What if the tuple is of arbitrary length? How can I write a function to do this?
    – ankush981
    Commented Jul 26, 2016 at 8:36
  • First of all: You should not have tuples of arbitrary length. In those scenarios you should use lists. But… if you insist: AListOfTuples = generate:your_list_of_tuples(), [FirstTuple|_] = AListOfTuples, [X|_] = tuple_to_list(FirstTuple), X. Commented Dec 5, 2019 at 10:52
33

Given that you get exactly what you state, a list with one tuple, even easier would be (using element/2)

element(1, hd(L)).

A pattern matching variant like shk suggested is probably even nicer, depending on the context.

5

you could also consider using records syntax if you want some semantics embedded into your tuples

-record(x, {y, z}).

1> A = #x{y=b, z=c}.
2> A#x.y.
b

all records are in fact tuples and you dont have to worry about order of elements in that tuple nor about adding/removing elements.

Not the answer you're looking for? Browse other questions tagged or ask your own question.