Suppose I have several lists:


where there can be several hundred entries in each list. {xi,yi} are measured data which can have errors {dxi,dyi}. Additionally these do not need to be symmetric, e.g. {dxi,{dyin,dyip}}is also possible .

I want to write a function f[l_List] which checks the form of the given list and then proceed in different ways. Since the shape for a given list does not change, it is enough to check the first element.

For example:

g[l_List]:= If[ f[l[[1]]]=={{_,_},{_,_}} ,a ,b ]

Where a and b are further operations on that list. The problem I have is finding the correct formulation for the condition in the If-statement.

I came up with Dimensions[l[[1]]]=={1,2,2} which works for distinguishing lst1 and lst2, but fails for lst3, since Dimensions[lst1[[1]]]==Dimensions[lst3[[1]]]=={1,2,2}.

So the question is how this condition could look like.

Thanks in advance.

Additional question: How do I color my code like it is done in most questions on this side?

  • $\begingroup$ Indent your code by four spaces to get the code with syntax coloring (as opposed to inline code delimited by backticks). As for your actual problem, probably something like MatchQ[expr, {{_, _}, _}] might be useful. $\endgroup$ Aug 19, 2017 at 16:12
  • $\begingroup$ I am not exactly sure how I was able to overlook this, but it does the job. One just needs to check the most nested structure first for it to work. Thanks! $\endgroup$
    – ctrl
    Aug 19, 2017 at 16:34

1 Answer 1


You can simply use the pattern describing your structure on the left side of SetDelayed:

f[l : {{{_, _}, {_, _}} ..}] := "Structure 1"
f[l : {{{_, _}, _} ..}] := "Structure 2"
f[l : {{{_, _}, {_, {_, _}}} ..}] := "Structure 3"

You can read up on patterns in the documentation. Note that Mathematica always uses the most specific pattern that matches: Even though the first definition would also match lst3, it's not taken since the third one is more specific.

Now, the correct one of these 3 definitions is used, depending on the structure of the list:

In[1]:=  f[lst1]
Out[1]:= "Structure 1"
In[2]:=  f[lst2]
Out[2]:= "Structure 2"
In[3]:=  f[lst3]
Out[3]:= "Structure 3"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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