I'm doing some metaprogramming. How would I make a Mathematica function that returns a random Mathematica command? Is there a list of command names that I could use RandomChoice on?

I'm looking for something better than selecting random letters until getting Protected in the Attributes, which is all I've been able to think of so far.


3 Answers 3


There are a lot of commands! One way to get a list is to use Names["*"], which will return all the symbols Mathematica knows. Since commands start with capital letters, you can gain more control over the list by asking for only a subset. For example,

all = {"A*", "B*", "C*"};
Names[#] & /@ all

provides a list of all commands that start with A, B, or C. You could customize the all to suit your preferences.

  • 1
    $\begingroup$ Nowadays, one can use WolframLanguageData["RandomEntities"]. $\endgroup$ Commented Jun 7, 2016 at 10:01

Get the full list of Mathematica functions here:

myFunctionList = Import["http://reference.wolfram.com/language/guide/\

Strip the list of header and footer material, and select a random element:

RandomChoice[StringSplit[StringTake[myFunctionList, {3245, -1225}]]]

Or, based on the approach of bill s:

RandomChoice@Flatten[Names[#] & /@ (StringJoin[#, "*"] & /@ CharacterRange["A", "Z"])]

Here's a piece of code that lets you see random Wolfram Language code snippets, rather than just command names.

RandomExample[] := Module[{dir, file, inputs, output, cap, i = 0, j = 1, in},
    dir = DirectoryName[FindFile["ExamplePages/CreateMolecularGraphs.nb"]];
    file = RandomChoice[FileNames["*", dir]];
    output = Import[file, {"Cells", "Output"}][[1]];

    cap = CellLabel /. Options[output];
    If[!StringQ[cap], Return[$Failed]];
    cap = ToExpression[StringReplace[cap, "Out[" ~~ x__ ~~ "]" ~~ __ :> x]];

    inputs = Import[file, {"Cells", "Input"}];

        StringReplace[file, __ ~~ "ExamplePages" :> "ExamplePages"],

        While[i < cap && j <= Length[inputs],
            in = CellLabel /. Options[inputs[[j]]];
                i = ToExpression[StringReplace[in, "In[" ~~ x__ ~~ "]" ~~ __ :> x]]
    ][[-1, 1]]];


enter image description here enter image description here


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.