Tutorial: Lists

This brief tutorial walks you through a simple example using lists.

Consider the following code, which draws a square with its top-left corner at (x0, 100). As x0 increases, the square moves across the screen from right-to-left. Go ahead and copy it into p5.js so you can see what it does.

// Example #1

var x0;


function setup() {

  createCanvas(400, 400);

  x0 = 100;

}


function draw() {

  background(220);

  rect(x0, 100, 50, 50);

  x0 = x0 + 1;

}


Example #2 (below) makes 3 squares move across the screen in the same manner, with 3 copies of each part of the code. Go ahead and copy it into p5.js so you can see what it does.

// Example #2

var x0;

var x1;

var x2;


function setup() {

  createCanvas(400, 400);

  x0 = 100;

  x1 = 180;

  x2 = 300;

}


function draw() {

  background(220);

  rect(x0, 100, 50, 50);

  rect(x1, 100, 50, 50);

  rect(x2, 100, 50, 50);

  x0 = x0 + 1;

  x1 = x1 + 1;

  x2 = x2 + 1;

}


Example #3 (below) behaves exactly the same, but this version uses a single variable xvals containing a list. The setup function initializes xvals to a list containing 3 numbers: 100, 180, and 300. The draw function uses xvals[0], xvals[1], and xvals[2] to refer to the first, second, and third value in the list.

// Example #3

var xvals;


function setup() {

  createCanvas(400, 400);

  xvals = [100, 180, 300];

}


function draw() {

  background(220);

  rect(xvals[0], 100, 50, 50);

  rect(xvals[1], 100, 50, 50);

  rect(xvals[2], 100, 50, 50);

  xvals[0] = xvals[0] + 1;

  xvals[1] = xvals[1] + 1;

  xvals[2] = xvals[2] + 1;

}


Finally, example #4 (below) behaves exactly the same, but this version uses a loop to draw and move each of the 3 squares. Every time the draw function runs, the code inside the loop runs 3 times--first when i is 0, then again when i is 1, and again when i is 2.

// Example #4

var xvals;


function setup() {

  createCanvas(400, 400);

  xvals = [100, 180, 300];

}


function draw() {

  background(220);

  for (var i = 0; i <= 2; i = i + 1)

  {

    rect(xvals[i], 100, 50, 50);

    xvals[i] = xvals[i] + 1;

  }

}


Check Your Understanding