38 Assigning Names to Things

Particularly when you’re doing quick experiments in the Wolfram Language, it’s often convenient to use % to refer to the result of your most recent computation.

Do a simple computation: % gives the result of the previous computation: This squares the most recent result:

If you expect to refer to a result later, you can assign it a name. For example, you can say thing=Range[10] to assign thing as a name for the result of Range[10] .

Assign thing to be the result of Range[10] : thing = Range[10] Whenever thing appears, it’ll be replaced by the result of Range[10] : Square the value of thing :

You can assign a name to the result of a computation even if you never display the result. End your input with ; (semicolon) to avoid seeing the result.

Assign a name to a list of a million elements, but don’t display the list: millionlist = Range[1000000]; Find the total of all the elements in the list: Total[millionlist] Assign x the value 42: You might have thought this would be — but x has value 42: If you want to clear assignments, use Clear. Clear any assignment for x : Now x , like y and z , isn’t replaced:

Assigning a global value for x , like x=42 , is potentially a big deal, because it can affect everything you do in your session (at least until you clear x ). Something that’s much safer — and extremely useful — is just to assign a temporary, local value to x , inside a module.

This locally sets the value of x to be Range[10] inside the Module: Outside the module, x still has no value assigned: You can have as many local variables inside a module as you want. Define local variables x and n , then compute x^n using the values you’ve assigned:

It’s still useful in the Wolfram Language, though in many ways it’s eclipsed by functional programming, as well as by the pattern-based style of programming that we’ll discuss later.

To specify sequences of actions in the Wolfram Language one just separates them by semicolons ( ; ). (Putting a semicolon at the end is like specifying an empty final action, which is why this has the effect of not displaying a result.)