代码之家  ›  专栏  ›  技术社区  ›  keitereth24

在Python中,if not myList和if myList是[]有什么区别?

  •  0
  • keitereth24  · 技术社区  · 8 年前

    我在写代码的时候遇到了一个小问题。我最初是这样的:

    if myList is []:
        # do things if list is empty
    else:
        # do other things if list is not empty
    

    this question

    if not myList:
        # do things if list is empty
    else:
        # do other things if list is not empty
    

    这使我的程序按我的预期工作(它运行“if not myList”部分,而不是“else”语句)。

    我的问题是,这个if语句的逻辑发生了什么变化?我的调试器(我使用Pycharm)说myList两次都是空列表。

    2 回复  |  直到 8 年前
        1
  •  5
  •   ForceBru    8 年前

    is id s、 因此 a is b == (id(a) == id(b)) 。这意味着这两个对象是 :它们不仅具有相同的值,而且还占用相同的内存区域。

    >>> myList = []
    >>> myList is []
    False
    >>> id([]), id(myList)
    (130639084, 125463820)
    >>> id([]), id(myList)
    (130639244, 125463820)
    

    [] 每次都有不同的ID,因为 每次都会分配一块新内存 .

        2
  •  1
  •   dreamriver    8 年前

    is 比较标识(同一对象)。较小的数字在启动时缓存,因此返回 True 在这种情况下,例如。

    >>> a = 1
    >>> b = 1
    >>> a is b
    True
    

    None [] .一般来说,你应该只使用 没有一个 或者在显式检查sentinel值时。你可以在使用 _sentinel = object()