Python lists and loops

Advanced

Lists use square brackets and zero-based indexes; len/sum/max/append are everyday tools; for walks through a list, while repeats by condition — beware infinite loops.

For:Secondary 2 Information & Communication Technology · Unit:Algorithms & programming · Lesson 5 of 12 in the learning path

After this lesson, you can:
  • Lists use [ ] and zero-based indexes.
  • len, sum, max, min and append are the everyday list tools.
  • A one-line average: sum(list) / len(list).
文體:編程教學課有聲朗讀

文體小知識:編程教學課每個概念都配一段可以親手試的代碼例子,照住輸入、改一改,最快學會。

資訊及通訊科技Information & Communication Technology

§Text Passage

1A list holds several pieces of data together, wrapped in square brackets and separated by commas, e.g. scores = [80, 92, 75]. Lists are numbered from 0: scores[0] is 80, scores[1] is 92, scores[2] is 75. This zero-based index is the classic beginner trap.

2Lists come with ready-made tools: len(scores) counts the items, sum(scores) totals them, max(scores) finds the largest, and scores.append(60) adds a new item at the end. A three-subject average takes one line: sum(scores) / len(scores). These tools make handling a whole class's scores effortless.

3The for loop suits going through a list one by one: for s in scores: assigns 80, then 92, then 75 to s in turn, running the indented loop body once per item. The while loop repeats as long as a condition holds, e.g. while total < 100: keep adding. With while you must make sure the condition eventually fails, or the loop never stops.

4In practice: a teacher stores the class's scores in a list and uses a for loop to check each one for a pass; a game uses a while loop to keep the character moving until health hits zero. Lists plus loops are the fundamental skill for processing large amounts of data.

1Summary 重點摘要

Lists use square brackets and zero-based indexes; len/sum/max/append are everyday tools; for walks through a list, while repeats by condition — beware infinite loops.

2Vocabulary cards Vocabulary

L
List清單

An ordered collection of data in square brackets, e.g. [80, 92, 75].

I
Index索引

The position number of an item in a list, starting at 0; scores[0] is the first item.

E
Element元素

One item in a list; a list can mix numbers and text.

a
append()加入元素

Adds a new item to the end of a list, e.g. scores.append(60).

l
len()長度函數

Returns how many items a list holds, e.g. len([10, 20, 30]) is 3.

f
for loopfor 迴圈

A loop that goes through a list or repeats a set number of times, e.g. for s in scores:.

w
while loopwhile 迴圈

A loop repeating while its condition holds, e.g. while total < 100:.

I
Infinite loop無限循環

A while loop whose condition never fails, usually because a variable is never updated.

r
range()範圍函數

Generates a sequence of integers for for loops, excluding the end: range(1, 6) gives 1 to 5.

3Step by step Steps

  1. Making a listA list keeps many pieces of data together, written in square brackets with commas: scores = [80, 92, 75]; print(scores) shows [80, 92, 75]. Lists mix types freely — ['Mary', 12, 'S1A'] holds a name, an age and a class at once. In practice a teacher keeps the whole class's marks in one list and a shop program keeps its products in another, managing a mass of data through a single variable and avoiding messy names like scores1, scores2, scores3.
  2. Indexes start at 0List numbering (the index) starts at 0: scores[0] is 80, scores[1] is 92, scores[2] is 75. A three-item list has only the legal indexes 0, 1, 2; asking for scores[3] raises IndexError, because a fourth slot simply does not exist. Zero-based counting is the classic beginner trap — intuitively the first item is number 1, but in code it is number 0. The last item is also reachable as scores[-1], with −1 counting from the end and −2 the one before, which is very handy for 'take the last item' tasks.
  3. Everyday built-in operationsLists ship with ready-made tools: len(scores) returns the length 3; sum(scores) totals 247; max(scores) finds 92; min(scores) finds the smallest. scores.append(60) adds a new item at the end, growing the list to [80, 92, 75, 60], and len(scores) then returns 4. Combined, the tools are powerful: one line, average = sum(scores) / len(scores), averages three subjects or thirty with no change at all — the greatest advantage code holds over hand calculation.
  4. The for loop goes one by oneThe for loop suits processing list items in turn: for s in scores: print(s) prints 80, then 92, then 75, with the variable s taking a different item each round. Indentation (spaces at the line's start) marks which statements belong to the loop body: print(s) is indented and runs once per round, while an unindented statement runs only once, after the loop ends. Indentation mistakes are the beginner's staple — forgetting it makes a line run once; adding it where it does not belong raises IndentationError and stops the program.
  5. for with rangerange lets a for loop repeat over a number sequence: for i in range(1, 6): print(i) prints 1, 2, 3, 4, 5, because range(1, 6) includes the start 1 but not the end 6 — include the head, exclude the tail. range(3) starts from 0 giving 0, 1, 2; range(2, 11, 2) adds a step of 2 giving 2, 4, 6, 8, 10. To print 'practice done' five times, write for i in range(5): print("practice done"). Keep the include-start, exclude-end rule firmly in mind: to reach 5, write range(1, 6).
  6. while repeats by conditionA while loop repeats as long as its condition holds: with n = 1, the pair while n <= 3: print(n) and n = n + 1 prints 1, 2, 3 and then stops. Omit n = n + 1 and n stays 1 forever, the condition never fails, and the program never halts — an infinite loop that must be killed by force. The discipline of while is guaranteeing the condition will eventually break: something inside the loop body must steer toward the end. A game character walking until health hits zero is the classic while scenario.
  7. Lists plus loops togetherLists combined with loops are the fundamental skill for bulk data. With the class scores [70, 85, 90, 55], one line for s in scores: plus if s >= 50: print("pass") judges every subject in turn, and sum(scores) / len(scores) gives the average. The strength is scale-independence: four subjects become forty and the program changes not a letter. Teachers tallying marks, shops counting stock and programs reading files line by line all rest on this list-plus-loop combination — worth practising until it is second nature.

4Diagrams Diagrams

Python 清單與循環 Lists & loopsfruits = ["蘋果", "香蕉", "橙"]for f in fruits:print(f)輸出三行:蘋果 → 香蕉 → 橙(自動逐個拎出來)清單 list一個變數裝一堆嘢,用 [] 包住循環 for逐個處理清單,唔使逐個寫縮排 indentPython 靠縮排分層次,錯位就錯組合起嚟:一堆數據 + 一個循環 = 批量處理——程式嘅日常
Fig. 1: Python lists and loops

5Worked example Example

Example: write a program to find the average of the four scores [70, 85, 90, 55] and print whether each one passes (50 or above).

  1. scores = [70, 85, 90, 55]; sum(scores) = 300.
  2. Average = 300 ÷ 4 = 75.0, computed with sum(scores) / len(scores).
  3. for s in scores: checks each in turn — 70 ≥ 50 pass, 85 pass, 90 pass, 55 pass.
  4. If one score were 45, it would print 'fail' — the check sits inside the loop, so every score is tested once.
  5. Answer: Average 75.0; all four scores are ≥ 50, all pass. Core code: for s in scores: if s >= 50: print(s, "pass").

6Common mistakes Mistakes

✗ scores[1] is the first item.
✓ Indexes start at 0: scores[0] is first, scores[1] is second.
✗ for and while are the same, either will do.
✓ Use for to walk through a list; use while only for condition-driven repetition of unknown count.
✗ No need to think about when a while condition turns False.
✓ If the condition never changes, the loop never ends; something inside must eventually break the condition.
✗ range(1, 5) runs 1, 2, 3, 4, 5.
✓ range excludes the end: range(1, 5) is 1, 2, 3, 4; include 5 with range(1, 6).
✗ append inserts the new item at the front.
✓ append adds at the end; to insert at a position use insert(position, value).

7Quick check Quick check

Q1If nums = [4, 8, 15], what is nums[0]?

Q2What does len([10, 20, 30, 40]) return?

Q3scores = [60, 45]; after scores.append(90), what is the list?

Q4What does for i in range(3): print(i) print?

Q5Which one loops forever? A. while n < 5: n = n + 1 B. while n < 5: print(n) (n stays 3)

8Recap Recap

  • Lists use [ ] and zero-based indexes.
  • len, sum, max, min and append are the everyday list tools.
  • A one-line average: sum(list) / len(list).
  • for walks through lists; range excludes its end value.
  • while repeats by condition — update the condition inside, or it never ends.

Other subjects in this grade

Same subject, other grades