Data Structures & Strings
You already know lists. Now let us meet the rest of the collection family — tuples and dictionaries — and learn strings as text you can index, search, and format. Bạn đã biết danh sách (list). Bây giờ hãy gặp phần còn lại của gia đình collection — tuple và dictionary — và học chuỗi (string).
📘 Section 1 — The Collection Family
A list stores many values in order and can be changed. Python has more collections for different jobs. Một list lưu nhiều giá trị theo thứ tự và có thể thay đổi. Python còn có các collection khác cho từng mục đích.
- List
[ ]— ordered, changeable. có thứ tự, thay đổi được. - Tuple
( )— ordered, but cannot change. có thứ tự, không đổi được. - Dictionary
{ }— pairs of key → value. cặp khóa → giá trị. - String
" "— a sequence of characters. một dãy ký tự.
Quick recap of lists / Ôn nhanh về list
Need a refresher on creating, indexing, and list methods? See the Python Lists lesson first. Cần ôn lại cách tạo, truy cập và các phương thức của list? Xem bài Python Lists trước.
📦 Section 2 — Tuples (Bộ giá trị)
A tuple is like a list, but it cannot be changed after you create it. Use it for data that should stay fixed. Tuple giống list nhưng không thể thay đổi sau khi tạo. Dùng cho dữ liệu cần giữ cố định.
python# Create with parentheses point = (3, 5) colors = ("red", "green", "blue") # Access by index — just like a list print(point[0]) # 3 print(colors[-1]) # blue
Tuples cannot change / Không thể thay đổi
pythonpoint = (3, 5) point[0] = 10 # ❌ TypeError: tuples cannot be changed
Unpacking / Giải nén
You can split a tuple into separate variables in one line. Bạn có thể tách một tuple thành các biến riêng trong một dòng.
pythonpoint = (3, 5) x, y = point print(x) # 3 print(y) # 5 # A common trick: swap two values a, b = 1, 2 a, b = b, a print(a, b) # 2 1
List or tuple? / List hay tuple?
Use a list when the data will change (a shopping cart). Use a tuple for fixed data (a coordinate, a date). Dùng list khi dữ liệu sẽ thay đổi; dùng tuple cho dữ liệu cố định.
🗂️ Section 3 — Dictionaries (Từ điển)
A dictionary stores key → value pairs, like a real dictionary maps a word to its meaning. Dictionary lưu các cặp khóa → giá trị, giống từ điển ánh xạ một từ tới nghĩa của nó.
python# key : value ages = {"Alice": 14, "Bob": 15} # Access by key print(ages["Alice"]) # 14 # Add or update ages["Charlie"] = 13 # add new ages["Alice"] = 15 # update existing # Remove del ages["Bob"]
Check keys with in / Kiểm tra khóa với in
pythonages = {"Alice": 14, "Bob": 15} print("Alice" in ages) # True print("Dan" in ages) # False
Looping over a dictionary / Duyệt từ điển
pythonages = {"Alice": 14, "Bob": 15} for name in ages: # keys print(name, ages[name]) for name, age in ages.items(): # key and value print(f"{name} is {age}") print(len(ages)) # 2 — number of pairs
Keys are unique / Khóa là duy nhất
Each key appears once. Assigning to an existing key replaces its value. Mỗi khóa xuất hiện một lần. Gán lại khóa cũ sẽ thay giá trị.
🔤 Section 4 — Strings as Sequences
A string is a sequence of characters, so you can index and slice it just like a list. Chuỗi là một dãy ký tự, nên bạn có thể truy cập và cắt lát như với list.
pythonword = "Python" print(word[0]) # P (first character) print(word[-1]) # n (last character) print(word[0:3]) # Pyt (slice: index 0,1,2) print(len(word)) # 6 (length)
Join and repeat / Nối và lặp
pythonfirst = "Hello" second = "World" print(first + " " + second) # Hello World (concatenation) print("ha" * 3) # hahaha (repetition)
Loop and search / Duyệt và tìm kiếm
pythonword = "banana" for letter in word: # go through each character print(letter) print("an" in word) # True — substring check
🛠️ Section 5 — String Methods
Strings have many built-in methods. Because strings are immutable, these methods return a new string — the original does not change. Chuỗi có nhiều phương thức sẵn có. Vì chuỗi bất biến, các phương thức trả về chuỗi mới — chuỗi gốc không đổi.
pythontext = " Hello World " print(text.upper()) # " HELLO WORLD " print(text.lower()) # " hello world " print(text.strip()) # "Hello World" (remove edge spaces) print(text.replace("o", "0")) # " Hell0 W0rld " print("Hello World".find("World")) # 6 (position, or -1 if missing) print("a,b,c".split(",")) # ['a', 'b', 'c'] print("-".join(["2026", "07", "24"])) # "2026-07-24" print("banana".count("a")) # 3
split and join are partners / split và join là cặp đôi
split turns a string into a list; join turns a list back into a string. split biến chuỗi thành list; join biến list thành chuỗi.
✨ Section 6 — f-strings (Định dạng chuỗi)
An f-string lets you put variables directly inside a string. Start the string with f and wrap values in { }. f-string cho phép đặt biến trực tiếp trong chuỗi. Bắt đầu bằng f và đặt giá trị trong dấu ngoặc nhọn.
pythonname = "Linh" age = 14 print(f"Hello {name}, you are {age} years old.") # Hello Linh, you are 14 years old. # Format numbers: .1f means 1 decimal place avg = 80.6666 print(f"Average = {avg:.1f}") # Average = 80.7
🧩 Section 7 — Putting It Together
Let us count how many times each word appears in a sentence — using a dictionary, split, and a loop together. Hãy đếm số lần mỗi từ xuất hiện trong một câu — dùng dictionary, split và vòng lặp cùng nhau.
pythonsentence = input("Enter a sentence: ") words = sentence.split(" ") counts = {} for word in words: if word in counts: counts[word] = counts[word] + 1 else: counts[word] = 1 for word, n in counts.items(): print(f"{word}: {n}")
Example / Ví dụ:
Enter a sentence: the cat sat on the mat
the: 2
cat: 1
sat: 1
on: 1
mat: 1📝 Section 8 — Practice Exercises
Exercise 1 — Rabbit Pairs
A farm has 1 pair of rabbits in month 1 and 1 pair in month 2. From month 3 on, the number of pairs each month is the two previous months added together. Read N and print how many pairs there are in month N. Trang trại có 1 cặp thỏ ở tháng 1 và 1 cặp ở tháng 2. Từ tháng 3, số cặp mỗi tháng bằng tổng hai tháng liền trước. Nhập N và in số cặp thỏ ở tháng N.
Example Input:
6Example Output:
8Update both at once / Cập nhật cùng lúc
Keeping the two most recent months in a and b is enough. Write the update as a, b = b, a + b — assigning line by line changes a first and gives the wrong answer. Chỉ cần giữ hai tháng gần nhất. Gán từng dòng sẽ sai vì a đã đổi trước khi tính b.
Exercise 2 — Build a Dictionary
Read 3 names and their ages, store them in a dictionary, then look one up by name. Đọc 3 tên và tuổi, lưu vào dictionary, rồi tra cứu một tên bất kỳ.
Example Input:
Alice 14
Bob 15
Chi 13
BobExample Output:
Bob: 15Exercise 3 — Word Count
Count how many times each word appears in a sentence. Đếm số lần mỗi từ xuất hiện trong một câu.
Example Input:
the cat sat on the matExample Output:
the: 2
cat: 1
sat: 1
on: 1
mat: 1Exercise 4 — Reverse a String
Read a word and print it backwards using slicing ([::-1]). Đọc một từ và in ngược lại bằng slicing.
Example Input:
PythonExample Output:
nohtyPExercise 5 — Count Vowels
Count the vowels (a, e, i, o, u) in a string using a loop. Đếm số nguyên âm trong một chuỗi bằng vòng lặp.
Example Input:
programming is funExample Output:
5Exercise 6 — Clean a Name
Read a name that may have extra spaces; print it stripped and in Title Case. Đọc một tên có thể thừa khoảng trắng; in ra sau khi bỏ khoảng trắng và viết hoa chữ đầu.
Example Input:
linh nguyen Example Output:
Linh NguyenExercise 7 — Split Fields
Read a comma-separated line and print each field on its own line. Đọc một dòng ngăn cách bằng dấu phẩy và in từng phần một dòng.
Example Input:
apple,banana,cherryExample Output:
apple
banana
cherryExercise 8 — Receipt Line
Read an item name and a price; print a receipt line like Apple .... $3.50, with the price showing exactly 2 decimal places. Đọc tên món và giá; in một dòng hóa đơn với giá có đúng 2 chữ số thập phân.
Example Input:
Apple
3.5Example Output:
Apple .... $3.50🚀 Section 9 — Challenge: Contact Book
Build a small contact book using a dictionary of name → phone number. Xây một sổ danh bạ nhỏ dùng dictionary tên → số điện thoại.
- Add a contact (name and phone). Thêm liên hệ.
- Look up a phone by name. Tra số theo tên.
- List all contacts. Liệt kê tất cả liên hệ.
Example Output:
add / find / list / quit: add
Name: Minh
Phone: 0987654321
add / find / list / quit: add
Name: Linh
Phone: 0901234567
add / find / list / quit: find
Name: Linh
Linh: 0901234567
add / find / list / quit: find
Name: Nam
Not found
add / find / list / quit: list
Minh: 0987654321
Linh: 0901234567
add / find / list / quit: quitpythoncontacts = {} while True: action = input("add / find / list / quit: ") if action == "add": name = input("Name: ") phone = input("Phone: ") contacts[name] = phone elif action == "find": name = input("Name: ") if name in contacts: print(f"{name}: {contacts[name]}") else: print("Not found") elif action == "list": for name, phone in contacts.items(): print(f"{name}: {phone}") elif action == "quit": break
Summary / Tóm tắt
- Tuple
( )— ordered and fixed; great for unpacking. có thứ tự, cố định; hợp để giải nén. - Dictionary
{ }— key → value; access by key, loop with.items(). khóa → giá trị; duyệt bằng .items(). - Strings — index, slice, and use methods like
split,join,replace. truy cập, cắt lát, và dùng các phương thức. - f-strings format text cleanly:
f"...". định dạng chuỗi gọn gàng.