Python 檢查 set 集合是否為空

本篇介紹如何在 python 檢查 set 集合是否為空,

使用 not operator 運算子

使用 not operator 運算子來檢查 set 集合是否為空,
同時也是官方推薦的作法,

1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
myset = set()
print(type(myset))
print(myset)

if not myset:
print('myset is empty')

結果輸出:

1
2
3
<class 'set'>
set()
myset is empty

使用 len 判斷長度

使用 len() 函式來檢查 set 集合是否為空,

1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
myset = set()
print(type(myset))
print(len(myset))

if len(myset) == 0:
print('myset is empty')

結果輸出:

1
2
3
<class 'set'>
0
myset is empty

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python set 集合用法與範例