Python Lab

Stage 1 · 30 min · Free

Lists

Store many values in one variable: creating lists, indexes, append, len, looping over a list, sum, max, min, split().

Objectives

Why learn this

A class has 40 learners and nobody creates 40 variables. A list keeps a whole sequence of values in one variable and lets you process them with a loop.

Concept

Lists are written in square brackets: diem = [8, 6, 9].

Indexes start at 0: diem[0] is 8. diem[-1] is the last item. Accessing an index that doesn't exist raises IndexError.

append(x) adds x at the end. len(lst) is the number of items. sum, max and min give the total, largest and smallest.

input().split() splits a 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:

8 6 10

Output:

Số bài: 3
Cao nhất: 10
Trung bình: 8.0

Line-by-line explanation

  1. Line 1: splits "8 6 10" into ["8", "6", "10"] and converts each item to a number: [8, 6, 10].
  2. Line 2: len gives 3.
  3. Line 3: max gives 10.
  4. Line 4: 24 / 3 = 8.0 (/ gives a float).

Common mistakes

ds = [1, 2, 3]
print(ds[3])

The list has 3 items, so indexes only go from 0 to 2: IndexError.

print(ds[2]) hoặc ds[-1]
ds = input().split()
print(sum(ds))

The items are still strings, so sum raises 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

2 practice tasks and 3 quiz questions

Write code right in the browser; the grader runs real Python and points to the exact line that's wrong.

Practice for free