Are these two python if statements same or not?

Viewed 63
data = [] if data is None else list(data)
data = list(data) if data else []

Someone asked if these two are same or not, and which one I preferred. I told him they are same, but he didn't seem to be satisfied by the answer. So, are they different or same, and which one do you prefer?

1 Answers

No, they are not the same.

You can reverse the first one, then you have

data = list(data) if data is not None else []

vs.

data = list(data) if data else []

Or you can reverse the 2nd one, then you have

data = [] if not data else list(data)

vs.

data = [] if data is None else list(data)

So your question boils down to

  • whether if data is not None is the same as if data or alternatively
  • whether if data is None is the same as if not data.

These are semantically different:

  • if data is None is only true if data is None,
  • if not data is true if data has any "falsey" value: e. g. None, 0, "", False, (), {}, [] etc.
Related