20.4. Testing and iterating over lists

| Chapter 20: Lists |

| 20.4. Testing and iterating over lists

If L is a list, we can interrogate it to see whether it does or does not contain (at least one instance of) any compatible value V:

if (value) is listed in (list of values):

This condition is true if the given value, which must be of a compatible kind, is one of those in the list. For instance, if L is our list of the numbers 2, 3, 5, 7 and 11 then 5 is listed in it but 6 is not.

if (value) is not listed in (list of values):

This condition is true if the given value, which must be of a compatible kind, is not one of those in the list.

We can also repeat running through a list (just as we can with table rows). Thus:

repeat with (a name not so far used) running through (list of values):

This phrase causes the block of phrases following it to be repeated once for each item in the given list, storing that value in the named variable. (The variable exists only temporarily, within the repetition.) Example: let L be {2, 3, 5, 7, 11, 13, 17, 19}; repeat with prime running through L: ... If the list is empty, nothing happens: the "..." phrase(s) are never tried.

In the next sections, we shall see that it is possible to change, reorder and resize lists. But it's important never to change a list that's being repeated through. The following:

> let L1 be {1, 2, 3, 4};
> repeat with n running through L1:
> remove n from L1;

leaves L1 containing {2, 4}, since the removals from the list cause it to shuffle back even while we repeat through it - a bad, bad idea.

Previous | Contents | Next