Lists keep order, repeats and an empty starting point
A list is a sequence written inside square brackets, with commas between its elements. [1,13,2] has three elements. ["Monday","school"] has two string elements. [] is the empty list, with zero elements. One variable name can refer to a list of any current length.
![A list preserves sequence and repeated occurrences. [] is a list with no elements, not an undefined variable.](/images/computational-thinking/week-5/list-basics.png)
Lists and mathematical sets differ. [1,2] and [2,1] are different lists because the order changes. [1,1,2] contains three occurrences. A set ignores repeated values and has no intrinsic sequence. We can use a list to represent a set of unique student IDs, but uniqueness is a property of how we build that list.
| Expression | Number of outer elements | Meaning |
|---|---|---|
| [] | 0 | Empty list |
| [3] | 1 | One numeric element |
| [3,3,25] | 3 | Three occurrences; two different values |
| [[3,53],[24,72]] | 2 | Two pair elements |
| ["May"] | 1 | One string, not three characters |
Many lists contain elements of one kind, such as only IDs or only words. Pairs and triples later in the week intentionally group different fields. Always state the meaning of each position instead of assuming every number in a list is a mark.
Try it yourself
Are [] and [0] the same?
Show explained answer
No. [] has no elements. [0] has one element, the number zero.
Try it yourself
How long is [[3,53],[24,72]]?
Show explained answer
The outer list has length 2. Each of its two elements is itself a list of length 2.
Try it yourself
Does foreach over [3,3,25] visit only two different IDs?
Show explained answer
It visits three positions. The repeated value 3 is processed twice unless you explicitly remove or skip duplicates.
