訪問 Python 元組的前端和後端元素
當需要訪問 Python 元組的前端和後端元素時,可以使用訪問方括號。
元組是一種不可變資料型別。這意味著,一旦定義的值就不能透過訪問其索引元素來改變。如果我們嘗試更改元素,它會導致錯誤。它們包含重要資訊,因為它們確保了只讀訪問。
以下是演示程式碼 −
示例
my_tuple_1 = (87, 90, 31, 85,34, 56, 12, 5)
print("The first tuple is :")
print(my_tuple_1)
my_result = (my_tuple_1[0], my_tuple_1[-1])
print("The front and rear elements of the tuple are : " )
print(my_result)輸出
The first tuple is : (87, 90, 31, 85, 34, 56, 12, 5) The front and rear elements of the tuple are : (87, 5)
說明
- 定義了一個元組,並在控制檯上顯示。
- 分別使用索引和負索引訪問元組的第一個元素和最後一個元素。
- 將其分配給一個值。
- 在控制檯上顯示為輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP