1-D arrays (lists)
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
A list holds many values
- A Python list stores many values under one name. We use it here to model an exam array.
- Write the items in square brackets, separated by commas.
- A Cambridge array has fixed declared bounds and elements of one data type. Python lists can grow and contain mixed types; they are not the same data structure.
English
scores = [40, 55, 72, 90]
print(scores)
English
Reach an item by its index
- Each item has a position number called its index.
- Python counts from 0, so the first item is
scores[0].

English
scores = [40, 55, 72, 90]
print(scores[0]) # 40
print(scores[2]) # 72
สำรวจ
Index and change a list
Items are numbered from 0; scores[0] is the first item.
English
Change an item
- Assign to an index to replace that one item.
English
scores = [40, 55, 72, 90]
scores[1] = 99
print(scores) # [40, 99, 72, 90]
English
Length and looping
len(scores)gives how many items there are.- A
forloop visits each item in turn.
English
scores = [40, 55, 72, 90]
print(len(scores)) # 4
for s in scores:
print(s)
English
In the exam: use the declared bounds
- Cambridge pseudocode states the lower and upper index bounds. A lower bound of 1 is usual, but not compulsory:
ARRAY[0:3]also has four cells, indexed 0 to 3.
DECLARE Scores : ARRAY[1:4] OF INTEGER
Scores[1] ← 40
OUTPUT Scores[1]
English
Common mistakes
- Python lists start at
0; the last non-negative index islength - 1. Cambridge arrays use their declared bounds. - Going past the end gives an index error.
English
Now you try
- Use an index, or a loop, on each list.
- Press Check answer to test your code.
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The list colours is set for you. Store its วินาที item in a variable called second (remember Python counts from 0).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Change the แรก item of the list nums ไป 99.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Use a loop to add up every number in nums and store the result in total (the answer is 43).
คลิก Run เพื่อดูผลลัพธ์ที่นี่