Modifying Lists

Math 213 - Math with Mathematica
Christopher Hanusa

Aim

This tutorial first starts off with some shortcuts to make your life with Mathematica easier.  Then we develop tools for creating, accessing, and modifying lists.

Tip: You can evaluate ALL cells in this file in order using the Evaluation > Evaluate Notebook command.

Defining variables using the = operator

It is often helpful to define the output of a command to be able to reuse it later.  To do this, use the = operator:

a=Range[3]

a

If you don’t want to see the output of a command, you can end the line with a semicolon.

a=Range[4];

a

Important: it matters the order in which you evaluate commands.  For example, if you re-evaluate the first instance of a, it will return its last-defined definition, which is {1,2,3,4}.

I HIGHLY suggest that you give descriptive names to your variables. Since all built-in Mathematica commands start with a captial letter, a nice convention to use for your own variable names is to start with a lowercase letter and if variable is multiple words long, capitalize the start of each new word.

iAmANewVariable=Range[Pi,2Pi,Pi/2]

heyYouWhatsThatSound=Play[Sin[440 2Pi t],{t,0,1}]

(OK, the provided example names aren’t very descriptive, but you get the idea....it’s #likeAHashtag.)

Shortcut: the % operator

A useful but slightly dangerous operator is %, which stands for the most recent output.  So, for instance, if you decide to make a list, and then decide you want to create a scatterplot, you can do the following:

Table[RandomInteger[{1,3}],{100}]

ListPlot[%]

The reason it is dangerous is related to the above discussion where the order in which you evaluate commands matters.  If you tried to re-evaluate the previous line of code, you would get an error, because you can’t create a scatterplot of a scatterplot!

ListPlot[%]

In the same vein is %% (for two outputs back); slightly more safe might be Out[n] to be explicit about wanting the nth output.  (But this will depend on the session in which you are working, so it would be different each time you re-open your notebook!!!!)  It is best to define a new variable when you think you will be using the output later.

Postfix a command using //

So let’s say you have created a beautiful command such as

Table[Range[i,10],{i,1,10}]

And then suppose you are at the end of the line and are too lazy to go to the beginning of the line to display the table in a beautiful way like this:

TableForm[Table[Range[i,10],{i,1,10}]]

Instead, you are able to use the // operator which applies the command after // to the start of the expression, like this:

Table[Range[i,10],{i,1,10}] // TableForm

When you’ve gotten yourself in trouble

When you don’t understand a command.

By now you should know that you can search in the Documentation Center when you want more information about a command.  You can get quick information about a command directly in a Mathematica notebook by using the ? operator.

?Tally

Notice the >> symbol at the end of the command information.  Click there to go directly to the Documentation Center.

When you define something you shouldn’t have.

Suppose you define a variable at some point:

x=10

Perhaps later in your file you wanted to generate the list {x+1,x+2,x+3} using the Table command:

Table[x+i,{i,3}]

Since x had been defined before, the generated list has no x’s in it.  When you run into such a problem, you use the Remove command:

Remove[x];
Table[x+i,{i,3}]

When your code won’t stop running

We all get into infinite loops sometimes or take on too much work.  To stop Mathematica in the middle of a calculation, use (Option-.) or (Ctrl-.)  (That’s a period!)  
Try it here after removing the (* and *) which I used to comment out the command.

(* For[i=0,i≥0,i++,i] *)

Comprehension Questions:

1. Practice using the % operator.  
First, define and evaluate some list of even numbers by way of a Range or Table command.  
Then divide the list by 2 to divide each entry by 2.  
Then add 10 to the list.
And then give a scatterplot of this final list.

2. Use the ? operator to learn about the commands First and Rest.

The Table command, Part 2

More Variables

The Table command can also create a list with two or more variables changing at a time.  Simply put two variable ranges as inputs.  In the following example, we consider all values of x from 1 to 3 and all values of y from 1 to 3 and multiply them together (because that's what the function x*y says to do).

Table[x*y,{x,3},{y,3}]

It is often a good idea to give the list of points you want to plot a descriptive name first.

More Complicated Functions

The Table command is much more powerful than simply creating lists of numbers.  For instance, you can create lists of anything in the language of Mathematica:

Graphics objects:

Table[Plot[x^n,{x,-2,2}],{n,0,10}]

Coordinates of a hexagon:

Table[{Cos[2π k/6],Sin[2π k/6]},{k,0,5}]
Graphics[Polygon[%]]

Pictures of polygons:

Table[Graphics[Polygon[Table[{Cos[2π k/i],Sin[2π k/i]},{k,0,i-1}]]],{i,3,10}]

Colors:

Table[ColorData["Rainbow"][x],{x,0,1,.1}]

The Periodic Table of the Elements:

Table[ElementData[i,"Abbreviation"],{i,1,100}]

Comprehension Questions:

3. For each of the following Table commands, complete the following sub-questions.
(a) BEFORE EVALUATING THE COMMAND, what list do you expect the command to give?  Or do you expect an error?
(b) Now, evaluate the command.  Did it do what you expect it to do?
(c) If not, figure out what went wrong with your reasoning.

Table[{s,7,9},{t,3,5}]

Table[{x,y},{x,2,4},{y,5,7}]

Table[xy,{x,2,4},{y,5,7}]

Table[Plot[x^n,{n,-2,2}],{x,1,10}]

Table[CountryData[country,"Population"],{country,{"France","United States","China"}}]

4. Create the table of possibilities of what happens when you roll two six-sided dice.  
What is their sum?  What is their product?  Evaluate and use these provided Table commands:

AddDice=Table[i+j,{i,1,6},{j,1,6}]
MultDice = Table[i*j,{i,1,6},{j,1,6}]

Does this do what you expect?  Now use TableForm to output AddDice and MultDice in a more readable format.

Useful list commands

Length

Length will tell you how many elements there are in the list.

Length[{1,2,3}]

Length[{1,{2,3}}]

Total

Total will sum the values in the list.

Total[{1,2,3}]

powersOfTen=Table[10^i,{i,0,5}]

Total[powersOfTen]

Flatten

When there are nested lists and you would like to remove some of the extra braces, you should use Flatten.

list=Table[x*y,{x,3},{y,3}]

Flatten[list]

You can also specify how many layers of braces you want to remove.

list2=Table[{x,y},{x,3},{y,3}]

Flatten[list2]

Flatten[list2,1]

Prepend and Append

When you want to add elements to the end of a preexisting list, use Append.  To add elements to the beginning, use Prepend.
This is often used in conjunction with redefining the preexisting list.

powersOfTen=Table[10^i,{i,0,5}]

Append[powersOfTen,10^6]

powersOfTen

Prepend[powersOfTen,0]

You can see that powersOfTen does not change when using Append or Prepend. 
You need to redefine powersOfTen if you want to actually add an entry to the list for future use.

powersOfTen=Append[powersOfTen,10^6]

powersOfTen

Accessing parts of lists

It is often useful to single out one or more of the entries of a list.  For this we use double square brackets [[n]], (same as Part).

powersOfTen[[5]]

Part[powersOfTen,5]

When the list is a nested list, you can reference an entry (a sublist) or even an entry of the sublist.

nestedList={{1,2},{3,4},{5,6}};

nestedList[[2]]

nestedList[[2,1]]

Comprehension Questions:

5. For each of the following commands, complete the following sub-questions.
(a) What list do you expect the command to give?  Or do you expect an error?
(b) Now evaluate the command.  Did it do what you expect it to do?
(c) If not, figure out what went wrong with your reasoning.

Length[{1,2,3,4}]

Length[{{1,2,3}}]

Total[{1,2,3,4}]

Total[{{1,2},{3,4}}]

Total[{{1,2,3}}]

Flatten[{{{{1},2},3},4}]

Flatten[{{{{1},2},3},4},2]

Append[{1,2,3,4},{1}]

Append[{{1,2},{3,4}},5,6]

Append[{{1,2},{3,4}},{5,6}]

Part[powersOfTen,6]

Part[powersOfTen,{1,3,5}]

Discuss these answers with your neighbors.

6. Consider rolling two dice and taking the sum of the values.  What is the average value for this sum?  What is the average value for the product of two rolled dice?  Three rolled dice?  Four?

7. Here are two lists which represent the x- and y-coordinates of points, and an incorrect Table command that hopes to collect the points into a list of ordered x,y pairs.  Figure out what is wrong with the command and fix it.

x={1,2,3,4,5}
y={2,5,10,17,26}
points=Table[{x[i],y[i]},{i,1,Length[x]}]

Solution:

You need to use double brackets to reference parts of a list.

points=Table[{x[[i]],y[[i]]},{i,1,Length[x]}]