Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between [None] and [] in python? [duplicate]

Tags:

python

list

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?

like image 909
minssi Avatar asked Apr 29 '16 02:04

minssi


2 Answers

[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 []).

like image 89
Frank Bryce Avatar answered Oct 20 '22 00:10

Frank Bryce


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.

For (equality) comparisons you shouldn't use 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.

like image 20
MSeifert Avatar answered Oct 20 '22 01:10

MSeifert