2
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?

Ashish Singh
  • 183
  • 1
  • 2
  • 9
  • See [What is Truthy and Falsy, in Python?](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) – smci Mar 26 '20 at 08:01

1 Answers1

2

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.
glglgl
  • 89,107
  • 13
  • 149
  • 217