Tuesday, February 27, 2018

Python None vs Empty list

>>> a=[]
>>> b=None
>>> type(a),type(b)
(<class 'list'>, <class 'NoneType'>)
>>> not a, not b
(True, True)
>>> a is None, b is None
(False, True)
>>> a is not None, b is not None
(True, False)
>>> a,b
([], None)

Tuesday, February 20, 2018

best way to check if a list is empty in Python3

Do it with:
if not a:
    print("a is an empty list.")

instead of:

if len(a):
    print("a is an empty list.")

Reference: Official Python programming recommendations
See the discussions on Stack Overflow

/ vs // in python3

Code speaks:


>>> a=b=5
>>> a,b
(5, 5)
>>> type(a), type(b)
(<class 'int'>, <class 'int'>)
>>> a/=2
>>> b//=2
>>> a,b
(2.5, 2)
>>> type(a), type(b)
(<class 'float'>, <class 'int'>)
>>> alist = list(range(10))
>>> alist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> alist[:a]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method
>>> alist[:b]
[0, 1]

Note if you are trying calculating the indices with '/' you would get trouble as showed above.