此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
A list holds many values
- A list keeps many values in one variable.
- Write the items inside square brackets:
[10, 20, 30]. - The items can be numbers, strings, or a mix.
English
Get and change items
- Use an index, just like a string:
nums[0]is the first item. nums[-1]is the last item.- You can also change an item:
nums[0] = 99.

English
fruits = ["apple", "pear", "plum"]
print(fruits[0])
print(fruits[-1])
English
Add items and count them
nums.append(x)addsxto the end of the list.len(nums)tells you how many items there are.- A list can grow as your program runs.
English
fruits = ["apple", "pear"]
fruits.append("plum")
print(len(fruits))
print(fruits)
English
Loop over a list
for item in nums:visits each item in turn.- The loop variable holds one item per pass.
- This is the easy way to process every value.
English
scores = [10, 20, 30]
total = 0
for s in scores:
total = total + s
print(total)
English
In Cambridge pseudocode
- A list is the exam's 1-D array. Note: exam arrays often start at index
1, but Python lists start at0.
DECLARE Scores : ARRAY[1:3] OF INTEGER
Scores[1] ← 10
Scores[2] ← 20
Scores[3] ← 30
FOR I ← 1 TO 3
OUTPUT Scores[I]
NEXT I
English
Common mistakes
- The first item is
a[0]and the last isa[-1];a[len(a)]is out of range. b = ashares one list.a.copy()makes a new outer list, but nested mutable items are still shared: it is a shallow copy.appendadds one item to the end.
English
Now you try
- Build or loop over a list in each task.
- Press Check answer to test your code.
探索
A list changes in place
A list is ordered and indexed; append/change/pop all modify it.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Create a list colors holding "red", "green", "blue". Then append "yellow" so the list has four items.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Loop over the list nums and add up its values. Store the total in total (the answer is 66).
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Find the largest value in nums with a loop. Start largest at the first item, then loop through nums and keep the bigger value. Store the answer in largest (it is 23).
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Build a 新的 列表 backwards with the items of nums in reverse order. Use a loop, and do not change nums itself.
点击“运行”查看此处输出。