Skip to content

Lists

Use the List block to create an ordered collection of text or numbers.

Get values from a list

The simplest use of a list is to create a list of values and then call each value individually. In this example, we're assigning a list of three numbers to the variable notesList. The program calls each value individually by referencing its position in the list: 1, 2, and 3. The program then uses each value with a frequency block to output a tone on the //code.Node speaker for 0.5 seconds (500 ms).

Using a loop

We can reduce the amount of code in the previous example by using a loop. The Loops category has a loop specifically for use with lists. This loop works like a counting loop, where the program calls each item in the list with each cycle of the loop. In this example, the loop assigns the j variable to the first list item (1), then repeats the code for the second list item (2), and repeats the code once more for the last list item (3).

Create a list from text

You can create lists from a string of text containing multiple values separated by a delimiter. In this example, we create a list of numbers by entering values in a text block and separating them with a comma. In the list block, we also tell the program to use the comma as the delimiter. As a result, the //code.Node speaker outputs the frequencies of 261, 327, 418, and 192, playing each for 0.5 seconds.

Create a list one value at a time

You can set a variable from a list of numbers one value at a time. In this example, set a variable to a list containing three different integers. In the loop, the //code.Node speaker plays the frequencies of the #1 and #3 values in the list, changes the first and last values of the list, and plays those values again.

The speaker output in the second round sounds different than the first round because the code changed the frequencies after going through the loop one time. The end result is that the //code.Node speaker outputs the frequencies 491 and 182.

Create an array of values

An array is a list within a list. This is useful for passing values to an instruction that has more than one parameter. For example, the //code.Node RGB LED block has three parameters to create a particular color: red (R), green (G), and (B). An array is a convenient method to use if we want to change the color of the LED multiple times.

In the example below, we create four lists containing three values each and place them inside another list. This creates a 3×4 array assigned to the variable colorArray. A loop cycles through each row in the array, assigning the row to the rgbList variable. Inside the loop, we assign the 1st, 2nd, and 3rd value in the row to the redValue, greenValue, and blueValue variables, respectively. These variables are then used in the RGB LED block to create a color. As a result, the //code.Node RGB LED outputs green, red, blue, and yellow for 0.5 seconds each.