Bài trước: Python căn bản (17): Python Tuples
[Từ điển]
18. Python Tuples (cont.)
18.1 Update Tuple
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
But there are some workarounds.
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
Or you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an
error because the tuple no longer exists
18.3 Unpack Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple.
Example
Packing a tuple:
fruits = ("apple", "banana", "cherry")
But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking".
Example
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list.
Example
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.
Example
Add a list of values the "tropic" variable:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
18.4 Exercise
1. You cannot change the items of a tuple, but there are workarounds. Which of the following suggestions will work?
A. Convert tuple into a list, change item, convert back into a tuple.
B. Convert tuple into a set, change item, convert back into a tuple.
C. Convert tuple into a dictionary, change item, convert back into a tuple.
D. Convert tuple into a string, change item, convert back into a tuple.
2. Which is the correct syntax to delete a tuple?
A. delete mytuple
B. mytuple.delete()
C. del mytuple
D. del (mytuple)
3. Consider the following code:
fruits = ('apple', 'banana', 'cherry')
(x, y, z) = fruits
print(y)
What will be the value of y?
A. apple
B. banana
C. cherry
D. None
4. Consider the following code:
fruits = ('apple', 'banana', 'cherry', 'mango')
(x, *y, z) = fruits
print(y)
What will be the value of y?
A. ['banana', 'cherry']
B. ['banana', 'cherry', 'mango']
C. ['cherry', 'mango']
D. ['apple', 'banana']
5. Write a Python program, with following requires:
- Create a tuple to contain 5 names of subjects: math, literature, english, biology, physics
- Use the for loop to enter the scores of each subjects from the keyboard
- Calculate and print the GPA of the student.
-----
The answer hints:
1(A), 2(C), 3(B), 4(A)
5. Write a Python program, with following requires:
- Create a tuple to contain 5 names of subjects: math, literature, english, biology, physics
- Use the for loop to enter the scores of each subjects from the keyboard
- Calculate and print the GPA of the student.
[code18_5.py]
subjects = ("Math", "Literature", "English", "Biology", "Physics")
scores = []
for subject in subjects:
score = float(input(f"Enter score
for {subject}: "))
scores.append(score)
gpa = sum(scores) / len(scores)
print(f"GPA: {gpa:.2f}")
Cập nhật: 8/11/2024
Bài sau: Python căn bản (19):
-----
[Nội dung tham khảo từ w3schools và Internet]
Bạn muốn học Python căn bản tại Đà Lạt, liên hệ