# Python `len()`函數
> 原文: [https://thepythonguru.com/python-builtin-functions/len/](https://thepythonguru.com/python-builtin-functions/len/)
* * *
于 2020 年 1 月 7 日更新
* * *
`len()`函數計算對象中的項目數。
其語法如下:
```py
len(obj) -> length
```
| 參數 | 描述 |
| --- | --- |
| `obj` | `obj`可以是字符串,列表,字典,元組等。 |
這是一個例子:
```py
>>>
>>> len([1, 2, 3, 4, 5]) # length of list
5
>>>
>>> print(len({"spande", "club", "diamond", "heart"})) # length of set
4
>>>
>>> print(len(("alpha", "beta", "gamma"))) # length of tuple
3
>>>
>>> print(len({ "mango": 10, "apple": 40, "plum": 16 })) # length of dictionary
3
```
試試看:
```py
# length of list
print(len([1, 2, 3, 4, 5]))
# length of set
print(len({"spande", "club", "diamond", "heart"}))
# length of tuple
print(len(("alpha", "beta", "gamma")))
# length of dictionary
print(len({ "mango": 10, "apple": 40, "plum": 16 }))
```
具有諷刺意味的是,`len()`函數不適用于生成器。 嘗試在生成器對象上調用`len()`將導致`TypeError`異常。
```py
>>>
>>> def gen_func():
... for i in range(5):
... yield i
...
>>>
>>>
>>> len(gen_func())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'generator' has no len()
>>>
```
試一試:
```py
def gen_func():
for i in range(5):
yield i
print(len(gen_func()))
```
## `len()`與用戶定義的對象
* * *
要在用戶定義的對象上使用`len()`,您將必須實現`__len__()`方法。
```py
>>>
>>> class Stack:
...
... def __init__(self):
... self._stack = []
...
... def push(self, item):
... self._stack.append(item)
...
... def pop(self):
... self._stack.pop()
...
... def __len__(self):
... return len(self._stack)
...
>>>
>>> s = Stack()
>>>
>>> len(s)
0
>>>
>>> s.push(2)
>>> s.push(5)
>>> s.push(9)
>>> s.push(12)
>>>
>>> len(s)
4
>>>
```
試一試:
```py
class Stack:
def __init__(self):
self._stack = []
def push(self, item):
self._stack.append(item)
def pop(self):
self._stack.pop()
def __len__(self):
return len(self._stack)
s = Stack()
print(len(s))
s.push(2)
s.push(5)
s.push(9)
s.push(12)
print(len(s))
```
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象