Lists
| English | Chinese | Pinyin |
|---|---|---|
| list | 列表 | liè biǎo |
| elements | 元素 | yuán sù |
| ordered collection | 有序集合 | yǒu xù jí hé |
| index | 索引 | suǒ yǐn |
| traverse | 遍历 | biàn lì |
| general | 通用 | tōng yòng |
| append | 追加 | zhuī jiā |
A list holds many elements
- A list 列表 stores an ordered collection 有序集合 of values, called elements 元素, under one name.
- A single list
coloursmight hold "red", "green", and "blue". - One name replaces many separate variables.
- The order is fixed, so each element has a definite position.
A list stores:
Many values, one name, in a fixed order.
Access by index
- You access or change an element using its index 索引 — its position in the list.
- In many languages the first element is at index $0$:
colours[0]is "red". - Read
colours[1]to get "green", or assign tocolours[2]to change it. - Always check where a language starts counting.
Access an element, or change the list?
Reading colours[1] accesses an element; append, insert, and remove change the list's contents.
If lists start at index 0, colours[0] in ["red","green","blue"] is:
Index 0 is the first element, "red".
Visiting every element of a list in turn with a loop is called ______ the list.
Traversal processes the whole list, whatever its size.
Traverse with a loop
- To process a whole list, use iteration to traverse 遍历 it.
- A loop visits every element in turn — first, second, third, and so on.
- The same loop works no matter how many elements the list holds.
- This is what makes list code so general 通用.
The append operation:
Append grows the list by one at the end.
Traversing [70, 85, 90] and adding each to a total gives what final total?
70 + 85 + 90 = 245.
The same traversal loop works whether the list has 3 elements or 300.
The loop refers to the list by name, making it general.
Change the contents
- Lists support operations that change their contents:
- append 追加 adds a new element to the end;
- insert adds an element at a chosen position; remove takes one out.
Total a list. scores holds [70, 85, 90]. Start total ← 0, then traverse: 70 → total 70; 85 → total 155; 90 → total 245. Final total 245. Append a fourth score and the same loop adds it too — no code change.
A list is an ordered collection of elements under one name, reached by index (often from 0). Traverse it with a loop to process every element, which keeps code general for any size. Lists also change: append, insert, and remove.