I have a list(kicks), and a function(fix). I am aware of the problem using Loop and Append or AppendTo. My question is why does the Flatten produce the desired output.


kicks = {6.28992, 1.78953, 4.67832, 3.85717, 4.15561, 7.9862, 8.02365,
         2.62077, 5.89348, 6.50246}


 fix[list_] := Module[{xos, comp, ct},
    comp = {};
    xos = If[list > 7, AppendTo[comp, list]];
    ct = Flatten[comp]]

fix[#] & /@ kicks

Output: {{}, {}, {}, {}, {}, {7.9862}, {8.02365}, {}, {}, {}}

Desired output:

{7.9862, 8.02365}

I want to understand why Flatten in this case does not work, and how to solve it while using Module.


1 Answer 1


You are applying Flatten inside the function that you map. Your flattened lists will still have the head List, and will produce the output you show. Instead you must either:

  • Flatten outside the function after mapping
  • Use Sequence as the head of the returned expression so that these are effectively flattened automatically.

The first is simply:

fix /@ kicks // Flatten
{7.9862, 8.02365}

The second would be something like:

fix2[list_] :=
  comp = {};
  If[list > 7, comp = {comp, list}];
  Sequence @@ Flatten[comp]

fix2 /@ kicks
{7.9862, 8.02365}

However, using this function outside of Map may cause strange results as Sequence is returned to the top level (and may be caught by things like $PrePrint on the way).


  • You do not need to embed fix in a new Function before mapping it: simply write fix /@ kicks
  • I presume that being aware of the problem with AppendTo you wanted a linked-lists format, so I included that in my fix2 example.
  • $\begingroup$ Sequence thats what I was looking for! Great thank you! $\endgroup$
    Commented Sep 25, 2013 at 20:56
  • $\begingroup$ @ALEXANDER You're welcome. $\endgroup$
    – Mr.Wizard
    Commented Sep 25, 2013 at 20:58
  • $\begingroup$ The "AppendTo problem" is AppendTo copies the list to generate the answer, right? $\endgroup$
    – Hector
    Commented Sep 26, 2013 at 1:01
  • 1
    $\begingroup$ @Hector every time you change the length of a list you cause the underlying (low level) array to be reallocated, therefore append operations take time proportional to the length of the list. You can therefore make fast appends by using the format list = {list, new} or list = {new, list}, and then flattening at the end. Also see Sow and Reap, and Internal`Bag and related functions (search). $\endgroup$
    – Mr.Wizard
    Commented Sep 26, 2013 at 5:28

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.