1. Giới thiệu
Tuple là cấu trúc dữ liệu cũng tương tự như list. Tuy nhiên chiều dài của tuple không thay đổi. Giống như hằng số.
Các phần tử của tuple được đặt trong dấu ngoặc tròn
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
t = ('Machine', 'Learning') | |
print(t) # ('Machine', 'Learning') | |
# Hoặc | |
t1 = tuple(('Machine', 'Learning')) | |
print(t1) # ('Machine', 'Learning') |
a. Truy cập các phần tử của tuple
Cũng giống như list hay chuỗi cách truy cập phần tử tương tự. Bạn đọc vui lòng xem lại bài trước
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
t = ('Practice', 'Machine', 'Learning') | |
# Lấy phần tử từ vị trí số 1 đến vị trí số 3 | |
# Lưu ý là vị trí bắt đầu từ 1 không phải từ 0 | |
print(t[1:3]) # ('Machine', 'Learning') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
t = ('Practice', 'Machine', 'Learning') | |
del t | |
print(t) # NameError: name 't' is not defined |
Thực chất tuple không thể thêm mới được tuy nhiên nếu ta tạo một biến mới là tổng của 2 tuple thì vẫn có thể chấp nhận được
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
t1 = ('Practice', 'Machine') | |
t2 = ('Learning', '!!!') | |
t = t1 + t2 | |
print(t) # ('Practice', 'Machine', 'Learning', '!!!') |
Tìm hiểu thêm các hàm khác tại đây
0 nhận xét:
Đăng nhận xét