SECTION 02 / 24

Lists keep order, repeats and an empty starting point

1 min read

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.
A list preserves sequence and repeated occurrences. [] is a list with no elements, not an undefined variable.

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.

ExpressionNumber of outer elementsMeaning
[]0Empty list
[3]1One numeric element
[3,3,25]3Three occurrences; two different values
[[3,53],[24,72]]2Two pair elements
["May"]1One 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.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑