如何在Python中建立空元組?
元組是Python程式語言的一種資料結構。它用於以有序的方式儲存多個由逗號分隔的值。
它是不可變的,這意味著一旦建立了元組,就不能執行任何操作,例如刪除、追加等。元組中的元素可以是int、float、string、binary資料型別,並且允許元素重複。它使用索引訪問元素。它允許元組中只有一個元素。
索引是用於從特定資料結構訪問元素的概念。執行索引有兩種方式:正索引和負索引。在正索引中,起始元素的索引值為0,結束元素的索引值為元組的長度,而在負索引中,起始元素的索引值為-元組長度,結束元素的索引值為-1。
建立空元組有不同的方法。讓我們詳細瞭解每種方法。
括號()
tuple關鍵字
使用括號()建立元組
可以使用括號()建立空元組。
語法
語法如下所示。
variable_name = ()
其中,
變數名是元組的名稱
()是建立空元組的符號
示例
正如你在下面的例子中看到的,當我們將括號"()"賦值給一個變數時,就會建立一個空元組。
tuple1 = () print("The empty tuple created using brackets: ",tuple1) print(type(tuple1))
輸出
The empty tuple created using brackets: () <class 'tuple'>
示例
在這個例子中,我們使用括號建立了一個空元組。由於Python中的元組是不可變的,當我們嘗試向其中追加值時,會產生錯誤。
tuple1 = () print("The empty tuple created using brackets: ",tuple1) tuple1[0] = 10 print(type(tuple1))
輸出
('The empty tuple created using brackets: ', ())
Traceback (most recent call last):
File "main.py", line 3, in <module>
tuple1[0] = 10
TypeError: 'tuple' object does not support item assignment
使用tuple()函式
可以使用Python中提供的tuple()函式建立空元組。
語法
語法如下。
variable_name = tuple()
其中,
變數名是元組的名稱
tuple是建立空元組的關鍵字
示例
在這裡,當我們將函式tuple()賦值給一個變數時,就會建立一個空元組。
tuple1 = tuple() print("The empty tuple created using brackets, ",tuple1) print(type(tuple1))
輸出
The empty tuple created using brackets, () <class 'tuple'>
示例
在這個例子中,我們使用tuple關鍵字函式建立了元組,當我們嘗試追加元素時,由於元組是不可變的,會引發錯誤。
tuple1 = tuple() print("The empty tuple created using brackets, ",tuple1) tuple1[0] = "Niharika" print(type(tuple1))
輸出
以下是使用tuple關鍵字建立的空元組的輸出。
('The empty tuple created using brackets, ', ()) Traceback (most recent call last): File "main.py", line 3, in <module> tuple1[0] = "Niharika" TypeError: 'tuple' object does not support item assignment
廣告