Search code examples
pythonlistif-statementempty-list

What's the difference between if not myList and if myList is [] in Python?


I was working on some code when I ran into a little problem. I orginally had something like this:

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

When I ran the program (and had it so myList was empty), the program would go straight to the else statement, much to my surprise. However, after looking at this question, I changed my code to this:

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

This made my program work as I'd expected it to (it ran the 'if not myList' part and not the 'else' statement).

My question is what changed in the logic of this if-statement? My debugger (I use Pycharm) said that myList was an empty list both times.


Solution

  • is compares objects' ids, so that a is b == (id(a) == id(b)). This means that the two objects are the same: not only they have the same value, but they also occupy the same memory region.

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

    As you can see, [] has a different ID every time because a new piece of memory is allocated every time.