python 判空

is 和 == 的区别

  • is 对比的是地址
  • == 对比值

判空的常见规则

  1. 对于可变数据结构(list dict set)
l = []
if l:
    print('true')
  1. 对于不可变数据,一般使用 ==
  2. 对于 None,总是使用 is
>>> a = []
>>> b = []
>>> id(a)
4348985152
>>> id(b)
4349049280

>>> c = None
>>> d = None
>>> id(c)
4346080224
>>> id(d)
4346080224

refs: https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_language_rules/#true-false

posted @ 2022-05-11 18:27  Jneeee  阅读(89)  评论(0编辑  收藏  举报