I think [None] is same as [], but in my test , maybe there is something...
>>>print len([])
0
>>>print len([None])
1
when should i use the None ? and []
and another interesting question
>>>c= []
>>>d= []
>>>print c is d
False
>>>a= 1
>>>b=1
print a is b
True
why empty list's id granting that is different?
[None]
does not mean that there is nothing in the list. None
is a keyword in python which has a special meaning. It is like NIL
or NULL
in other languages.
When you say [None]
, you are saying "I would like to have a list which contains the special object called None
". This is different than saying "I would like a list which contains no elements" (by typing []
).
None
is a valid element, but you can treat it like a stub or placeholder. So it counts as an element inside the list even if there is only a None
.
is
. Use ==
!Because is
can lead to strange behaviour if you don't know exactly when and how to use it. For example:
>>> 1900 is 1900
True
>>> a = 1900
>>> b = 1900
>>> a is b
False
>>> a, b = 1900, 1900
>>> a is b
True
This rather strange behaviour is explained for example in this question: Why does Python handle '1 is 1**2' differently from '1000 is 10**3'?
This won't happen when you use ==
:
>>> a == b
True
>>> 1900 == 1900
True
like one would expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With