為何 Python 中會有獨立的元組和列表資料型別?
提供獨立的元組和列表資料型別是由於兩者有不同的作用。元組不可變,而列表可變。這意味著,可以修改列表,但不能修改元組。
元組是序列,就像列表一樣。元組和列表之間的區別在於,與列表不同,元組無法更改,並且元組使用圓括號,而列表使用方括號。
我們來了解如何建立列表和元組。
建立基本元組
示例
首先,讓我們建立一個包含整數元素的基本元組,然後瞭解包含元組的元組
# Creating a Tuple mytuple = (20, 40, 60, 80, 100) # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple))
輸出
Tuple = (20, 40, 60, 80, 100) Tuple Length= 5
建立 Python 列表
示例
我們將建立一個包含 10 個整數元素的列表並顯示出來。用方括號將元素括起來。這樣,我們還顯示了列表的長度,以及如何使用方括號訪問特定元素 −
# Create a list with integer elements mylist = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180]; # Display the list print("List = ",mylist) # Display the length of the list print("Length of the List = ",len(mylist)) # Fetch 1st element print("1st element = ",mylist[0]) # Fetch last element print("Last element = ",mylist[-1])
輸出
List = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180] Length of the List = 10 1st element = 25 Last element = 180
我們能否更新元組值?
示例
如上所述,元組不可變,且無法更新。但是,我們可以將元組轉換為列表,然後進行更新。
我們來看一個示例 −
myTuple = ("John", "Tom", "Chris") print("Initial Tuple = ",myTuple) # Convert the tuple to list myList = list(myTuple) # Changing the 1st index value from Tom to Tim myList[1] = "Tim" print("Updated List = ",myList) # Convert the list back to tuple myTuple = tuple(myList) print("Tuple (after update) = ",myTuple)
輸出
Initial Tuple = ('John', 'Tom', 'Chris')
Updated List = ['John', 'Tim', 'Chris']
Tuple (after update) = ('John', 'Tim', 'Chris')
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP