0

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.

keitereth24
  • 117
  • 7
  • 3
    `myList is []` doesn't work, since it compares object *identity* rather than *equality*. – Fred Larson Aug 04 '17 at 19:55
  • 1
    Have you tried `if myList == []:`? – alvits Aug 04 '17 at 19:55
  • 2
    @alvits Ah, that worked. I guess I mixed up "is" and "==". – keitereth24 Aug 04 '17 at 19:57
  • 2
    Possible duplicate of [When is the \`==\` operator not equivalent to the \`is\` operator? (Python)](https://stackoverflow.com/questions/3647692/when-is-the-operator-not-equivalent-to-the-is-operator-python) – Fred Larson Aug 04 '17 at 19:58
  • 1
    https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce — not quite the same since strings are not mutable, but close enough. – Josh Lee Aug 04 '17 at 19:58
  • I'd suggest you type `help("is")` in the console and read the whole thing (or just the parts concerning `==` and `is`). It's as concise and complete explanation of comparisons as it gets – KGS Aug 04 '17 at 20:03

2 Answers2

5

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

In Python is compares for identity (the same object). The smaller numbers are cached at startup and as such they return True in that case e.g.

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

And None is a singleton. You are creating a new list object when you do []. Generally speaking you should only use is for None or when checking explicilty for a sentinel value. You see that pattern in libraries using _sentinel = object() as a sentinel value.

dreamriver
  • 1,291
  • 2
  • 15
  • 20