Python 元組 len() 方法



Python 元組 len() 方法返回元組中元素的數量。

元組是 Python 物件的集合,這些物件以逗號分隔,它們是有序且不可變的。元組是序列,就像列表一樣。元組和列表之間的區別在於:元組與列表不同,元組不能更改,元組使用圓括號,而列表使用方括號。

語法

以下是Python 元組 len() 方法的語法:-

len(tuple)

引數

  • tuple - 這是要計算元素數量的元組。

返回值

此方法返回元組中元素的數量。

示例

以下示例顯示了 Python 元組 len() 方法的用法。這裡我們建立了兩個元組 'tuple1' 和 'tuple2'。'tuple1' 包含元素:123、'xyz'、'zara',而 'tuple2' 包含元素:456、'abc'。然後使用 len() 方法檢索元組的長度。

tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print ("First tuple length : ", len(tuple1))
print ("Second tuple length : ", len(tuple2))

當我們執行以上程式時,它會產生以下結果:-

First tuple length :  3
Second tuple length :  2

示例

這裡,我們建立了一個元組 'tup',它包含字串元素。然後我們使用 len() 方法檢索此元組的字串元素的數量。

# Creating the tuple
tup = ("Welcome", "To", "Tutorials", "Point")
# using len() method
result = len(tup)
#printing the result
print('The length of the tuple is', result)

執行以上程式碼時,我們得到以下輸出:-

The length of the tuple is 4

示例

在這裡,我們建立了一個空元組 'tup'。然後使用 len() 方法返回此元組的長度。

# Creating an empty tuple
tup = ()
# using len() method
result = len(tup)
#printing the result
print('The length of the tuple is', result)

以下是以上程式碼的輸出:-

The length of the tuple is 0

示例

在以下示例中,我們建立了一個巢狀元組 'tup'。然後,我們使用 len() 方法獲取元組的長度。為了獲取巢狀元組的長度,我們使用巢狀索引和索引 '0'。

# creating a nested tuple
tup = (('1', '2', '3'), ('a', 'b', 'c'),('1a', '2b', '3c'), '123', 'abc')
result = len(tup)
print('The length of the tuple is: ', result)
# printing the length of the nested tuple
nested_result = len(tup[0])
print('The length of the nested tuple is:', nested_result)

以上程式碼的輸出如下:

The length of the tuple is:  5
The length of the nested tuple is: 3
python_tuples.htm
廣告