Ở bài học trước, bạn đã biết cách tạo danh sách và truy cập các phần tử. Trong phần này, chúng ta sẽ học một số xử lý cơ bản trên danh sách.
19.1 Xử lý phần tử
Thay đổi phần tử
Để thay đổi giá trị của một phần tử, bạn chỉ cần gọi tên Danh sách kèm chỉ số (index) của nó và gán giá trị mới.
Ví dụ: Thay đổi loại trái cây, ở phần tử thứ hai trong danh sách
trai_cay = ["táo", "chuối", "cam"]
trai_cay[1] = "xoài" # Thay "chuối" bằng "xoài"
print(trai_cay) # Kết quả: ['táo', 'xoài', 'cam']
Thêm phần tử
Để thêm phần tử mới vào danh sách, chúng ta có hai cách:
- append(): Thêm vào cuối danh sách
- insert(): Chèn vào một vị trí cụ thể
Ví dụ:
lop_hoc = ["An", "Bình"]
lop_hoc.append("Chi") # Thêm "Chi" vào cuối
lop_hoc.insert(1, "Dũng") # Chèn "Dũng" vào vị trí số 1
print(lop_hoc) # Kết quả: ['An', 'Dũng', 'Bình', 'Chi']
Xóa phần tử
Có nhiều cách để xóa một phần tử ra khỏi danh sách:
- remove(): Xóa theo giá trị cụ thể
- pop(): Xóa theo chỉ số (nếu không để chỉ số, nó sẽ xóa phần tử cuối cùng)
- clear(): Xóa toàn bộ các phần tử, chỉ còn lại một danh sách rỗng
Ví dụ:
do_choi = ["xe", "búp bê", "robot"]
do_choi.remove("xe") # Xóa "xe"
print(do_choi) # Kết quả: ["búp bê", "robot"]
do_choi.pop(0) # Xóa phần tử đầu tiên
print(do_choi) # Kết quả: ['robot']
do_choi.clear()
print(do_choi) # []
19.2 Xử lý danh sách
Duyệt qua danh sách
Chúng ta thường dùng vòng lặp for để duyệt qua từng phần tử và thực hiện công việc nào đó.
Ví dụ:
mon_an = ["rau xanh", "bánh tráng", "mì gói", "xúc xích"]
for x in mon_an:
print(f"Tôi thích ăn {x}")
Tạo danh sách mới
Đây là cách viết ngắn gọn để tạo ra một danh sách mới từ danh sách cũ chỉ trên một dòng lệnh.
Ví dụ: Tạo danh sách mới chỉ chứa các trái cây có chữ "a"
trai_cay = ["táo", "chuối", "kiwi", "cam"]
moi = [x for x in trai_cay if "a" in x]
print(moi) # Kết quả: ['táo', 'chuối', 'cam']
Sắp xếp các phần tử trong danh sách
Bạn có thể sắp xếp các phần tử trong danh sách theo thứ tự bảng chữ cái hoặc theo giá trị từ nhỏ đến lớn bằng phương thức sort().
Ví dụ:
diem_so = [8, 5, 10, 7]
diem_so.sort() # Sắp xếp tăng dần
print(diem_so) # Kết quả: [5, 7, 8, 10]
Sao chép danh sách
Bạn không thể sao chép danh sách bằng cách viết list2 = list1 vì khi bạn sửa list1 thì list2 cũng bị sửa theo. Hãy dùng phương thức copy().
Ví dụ:
diem_so1 = [7, 5, 8 ]
diem_so2 = diem_so1.copy()
print(diem_so2) # [7, 5, 8]
Một số phương thức khác
Python cung cấp một số hàm khác để làm việc với danh sách:\
- len(): Đếm xem danh sách có bao nhiêu phần tử
- count(): Đếm một giá trị xuất hiện bao nhiêu lần
- reverse(): Đảo ngược thứ tự các phần tử trong danh sách
19.3 Bài tập và câu hỏi
Bài tập
Bài 19a. Nhật ký phép tính
Yêu cầu: Tạo một danh sách lich_su = []. Sử dụng vòng lặp while để cho người dùng thực hiện không giới hạn các phép tính (+, -, *, /). Mỗi khi người dùng thực hiện một phép tính (ví dụ: 5 + 3 = 8), hãy dùng append() để lưu chuỗi "5 + 3 = 8" vào danh sách. Cuối cùng, in toàn bộ lịch sử ra màn hình bằng vòng lặp for.
Bài 19b. Máy tính cộng nhiều số Yêu cầu: Cho người dùng nhập vào một dãy số cách nhau bởi dấu phẩy (ví dụ: "10,20,30"). Sử dụng split(",") để biến nó thành một danh sách, sau đó dùng vòng lặp for để tính tổng tất cả các số đó.
Câu hỏi ôn tập
Câu 19.1: Để thêm một phần tử vào đầu danh sách, bạn sử dụng lệnh nào?
A. append()
B. insert(0, giá_trị)
C. add()
D. push()
Câu 19.2: Lệnh trai_cay.sort(reverse=True) sẽ làm gì?
A. Xóa toàn bộ danh sách
B. Sắp xếp danh sách theo thứ tự tăng dần
C. Sắp xếp danh sách theo thứ tự giảm dần/ngược bảng chữ cái
D. Đảo ngược danh sách mà không sắp xếp
Câu 19.3: Kết quả của đoạn mã sau là gì?
ds = [1, 2, 3]; ds.pop(); print(ds)
A. [1, 2, 3]
B. [2, 3]
C. [1, 3]
D. [1, 2]
19. List Operations
In the previous lesson, you learned how to create lists and access elements. In this section, we will explore fundamental list operations.
19.1 Element Operations
Modifying Elements
To change the value of an element, simply reference the List name along with its index and assign a new value.
Example: Changing the second fruit in the list
fruits = ["apple", "banana", "orange"]
fruits[1] = "mango" # Replaces "banana" with "mango"
print(fruits) # Output: ['apple', 'mango', 'orange']
Adding Elements
There are two primary ways to add new elements to a list:
- append(): Adds an element to the end of the list
- insert(): Inserts an element at a specific index
Example:
classroom = ["An", "Binh"]
classroom.append("Chi") # Adds "Chi" to the end
classroom.insert(1, "Dung") # Inserts "Dung" at index 1
print(classroom) # Output: ['An', 'Dung', 'Binh', 'Chi']
Removing Elements
There are several ways to remove elements:
- remove(): Removes a specific value
- pop(): Removes an element by index (if no index is provided, it removes the last item)
- clear(): Removes all elements, leaving an empty list
Example:
toys = ["car", "doll", "robot"]
toys.remove("car") # Removes "car"
print(toys) # Output: ["doll", "robot"]
toys.pop(0) # Removes the first element
print(toys) # Output: ['robot']
toys.clear()
print(toys) # Output: []
19.2 List Processing
Iterating through a List
We typically use a for loop to iterate (loop) through each element to perform an action.
Example:
dishes = ["green veggies", "rice paper", "instant noodles", "sausage"]
for x in dishes:
print(f"I like eating {x}")
List Comprehension
This is a concise way to create a new list from an existing one in a single line of code.
Example: Create a new list containing only fruits that have the letter "a"
fruits = ["apple", "banana", "kiwi", "orange"]
new_list = [x for x in fruits if "a" in x]
print(new_list) # Output: ['apple', 'banana', 'orange']
Sorting Elements
You can sort elements alphabetically or numerically (ascending) using the sort() method.
Example:
scores = [8, 5, 10, 7]
scores.sort() # Sorts in ascending order
print(scores) # Output: [5, 7, 8, 10]
Copying a List
You cannot copy a list using list2 = list1 because modifying list1 will also change list2 (they point to the same object). Use the copy() method instead.
Example:
scores1 = [7, 5, 8]
scores2 = scores1.copy()
print(scores2) # Output: [7, 5, 8]
Other Built-in Methods
Python provides additional functions for list manipulation:
- len(): Returns the number of elements in the list
- count(): Counts how many times a specific value appears
- reverse(): Reverses the order of elements in the list
19.3 Exercises and Review
Exercises
Exercise 19a. Calculation Log
Requirement: Create a list history = []. Use a while loop to allow the user to perform unlimited calculations (+, -, *, /). Each time a calculation is performed (e.g., $5 + 3 = 8$), use append() to save the string "5 + 3 = 8" into the list. Finally, print the entire history using a for loop.
Exercise 19b. Multi-number Calculator
Requirement: Have the user input a series of numbers separated by commas (e.g., "10,20,30"). Use split(",") to convert it into a list, then use a for loop to calculate the sum of all those numbers.
Review Questions
Q 19.1: Which command is used to add an element to the beginning of a list?
A. append()
B. insert(0, value)
C. add()
D. push()
Q 19.2: What does the command fruits.sort(reverse=True) do?
A. Clears the entire list
B. Sorts the list in ascending order
C. Sorts the list in descending/reverse alphabetical order
D. Reverses the list without sorting
Q 19.3: What is the output of the following code? ds = [1, 2, 3]; ds.pop(); print(ds)
A. [1, 2, 3]
B. [2, 3]
C. [1, 3]
D. [1, 2]