PyPython Lab

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

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

  1. Line 1: split "8 6 10" into ["8", "6", "10"], convert each element 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 (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

Practice 2 exercises and 3 quick questions

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

Practice free