Stage 1 · 30 minutes · Free
Lists
Store many values in one variable: create lists, indices, append, len, loop over lists, sum, max, min, split().
Objectives
- Create lists and access elements by index
- Add and change elements
- Loop over lists with for
- Use len, sum, max, min
- Read many numbers on one line with split()
Why learn this
A class has 40 students, nobody creates 40 variables. A list holds a whole sequence of values in one variable and processes them with a loop.
Concept
A list is written in square brackets: diem = [8, 6, 9].
Indices start at 0: diem[0] is 8. diem[-1] is the last element. Accessing a missing index causes IndexError.
append(x) adds x at the end. len(ds) is the number of elements. sum, max, min compute the total, largest, smallest.
input().split() splits one line into a list of strings; use [int(x) for x in input().split()] or list(map(int, input().split())) to get a list of numbers.
Syntax
ds = [1, 2, 3]
ds.append(4)
print(ds[0], len(ds))
for x in ds:
print(x)
Example
diem = list(map(int, input().split()))
print("Số bài:", len(diem))
print("Cao nhất:", max(diem))
print("Trung bình:", sum(diem) / len(diem))Input data:
8 6 10
Output:
Số bài: 3 Cao nhất: 10 Trung bình: 8.0
Line-by-line walkthrough
- Line 1: split "8 6 10" into ["8", "6", "10"], convert each element to a number: [8, 6, 10].
- Line 2: len gives 3.
- Line 3: max gives 10.
- Line 4: 24 / 3 = 8.0 (the / operator gives a real number).
Common mistakes
ds = [1, 2, 3]
print(ds[3])The list has 3 elements, indices only run 0 to 2: IndexError.
print(ds[2]) hoặc ds[-1]ds = input().split()
print(sum(ds))The elements are still strings, sum reports TypeError.
ds = list(map(int, input().split()))ds.append(4, 5)append takes only one value.
ds.append(4) rồi ds.append(5), hoặc ds.extend([4, 5])Summary
- Lists in square brackets, indices from 0.
- append, len, sum, max, min are everyday tools.
- split() + map(int, ...) to read many numbers on one line.
Write code right in the browser; the grader runs real Python and points to the exact wrong line.
Practice free