Lists are what we refer to as a Data Structure, in Computer Science terms. This is a fancy term meaning that we have a well defined mechanism to store data in a well defined mechanism for future access. In a List, we are storing multiple values within a single variable, which allows us to store data that is related in one central location.
There are two was in which we can create a list in blockly. The first way is to just create a completely empty list, using the block. This creates a list which stores absolutely nothing, and you'll have to add items to it later. The other way to create a list is to initialize it with some set of values, using the block. This block allows you to exhaustively list all of the items which will exist in the list from the beginning, such as:
The above block creates a list called my_list, and stores in it the integers 1 - 5. For the time being, we will ALWAYS be using the create with blocks, but keep in mind the other block exists for future programs.
As you probably noted, the default block doe not have space for 5 elements by default. You can add an extra slot by pressing the icon inside the block. This will open the list sub-menu, where you can drag new item blocks into the list descriptor to add or remove space from the list:
Once we have created a list, we need to be able to do things with the list. Since a list stores multiple values in one location, we need a special block in order to retrieve an individual value. This block is the block. This block has two slots in it: The first allows you to specify which list you are operating on, and the second slot allows you to specify which location in the list to read from.
The above block will give you the 3rd element from the above created list, which will be the value 3. This block:
Will give you the 5th element from the above created list, which will be the value 5. If you try to access a value from a location which is not defined within the list, you will always get undefined
The above referenced blocks only allow you to access a single value from the list, which makes it no more useful than a regular variable. We can make this much more useful by using for loops to iterate over the list:
1 2 3 4 5
Notice that we are using a count loop here, which gives us a variable i to use within the loop. This is going to be our index to use in our list. Our lists always start with index 1, and continue up to the number of elements in the list. We can access the number of elements in the list by using the block, as shown in the above program.
For the following Blockly programs, determine what the value that appears in the alert dialog will be. You can check your answer with the environment below.