Lists

How do you do something to every item in a list?

Data lists are found in many apps. When you use Facebook, for instance, there is a list of your friends, a list of your status updates, etc. In your own app, you might keep track of your friends phone numbers, a list of your past scores in a game, or the number of miles you ran each day last week. With just about any software, there is probably data lists involved.

App Inventor, like most languages, provides a way to process the items of a list, to perform the same operation on each item. With App Inventor, you typically use a for each in list block. Check out the following examples:

Example 1. How do you send a text to a list of your friends?

The list phoneNumberList is defined at the top. It has “concrete” data (e.g., the three fictitious phone numbers). Most apps store dynamic, user-generated data, but for this example we’ll focus on the processing when you have a list.

The blocks inside the for each block are repeated for each item in the given list phoneNumberList. In this case, there are three items, so the three inner blocks will be repeated three times. Nine total blocks will be executed (“executed” is the computer science term for performing the operation that the block defines. Don’t worry, nobody is being killed!). The text “Missing you” will be sent to all three numbers. The for each in list is called a “loop” because the app loops up to the top of the for each after executing the bottom inner block. In computer science terminology, we say the app iterates through the items.

The parameter item defined in the for each is a placeholder and always holds the current item being processed. The first time through the loop it is “111-1111”. The second time through it is “222-2222”, and the third time it is “333-3333”. Thus all the numbers are sent the message.


Example 2. How do you add up a list of numbers?

The list of numbers in this example is fixed, but generally the list would be dynamic, user-generated data, e.g., in a workout app the user would enter the miles they ran each day and the data would be stored in a list.

The for each in list block is used to iterate through the numbers. item is the placeholder variable-- it holds the current number each time the row of blocks within the for each is executed. The first time item is 7, then 3, then 11, then 5. The variable total is defined to store the running sum. On the first iteration, total is set to its previous value (0) plus item, which is 7, so it becomes 0+7=7. On the second iteration, total is set to its previous value (7) plus item, which is 3, so it becomes 7+3=10. After the third iteration total is 21 and after the fourth iteration total is 26 and the foreach completes. After the for each loop, the total is displayed in a label (so someone will see the fruits of the apps labor!).