C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Instead: The len() built-in raises a TypeError. The NoneType has no len() method.
Built-insLenTip: If a variable may equal None, we must first use an if-statement to check for this condition.
Python program that assigns to None
# Get length of this string.
s = "value"
print(len(s))
# Cannot get length of None.
s = None
print(len(s))
Output
5
Traceback (most recent call last):
File "...", line 7, in <module>
print(len(s))
TypeError: object of type 'NoneType' has no len()
However: If the parameter "v" happens to equal None, we instead print a special value (-1). This avoids the TypeError.
Python program that tests None
def test(v):
# Test for None.
# ... Print -1 for length if None.
if v != None:
print(len(v))
else:
print(-1)
# Use None argument.
test(None)
# Use string argument.
test("hello")
Output
-1
5
Get: This method returns None. We test for this in an if-statement. We often cannot use the result of get() directly.
Tip: Here None acts as a special value to the dictionary meaning "not found." None can have special meanings based on the type.
DictionaryPython program that uses dictionary, None
items = {"cat" : 1, "dog" : 2, "piranha" : 3}
# Get an element that does not exist.
v = items.get("giraffe")
# Test for it.
if v == None:
print("Not found")
Output
Not found
And: When these values are None, they instead point to no objects. This means the objects are "not present."
So: When you try to use len() on a None list or string, you get a TypeError. It does not return zero even though there are no elements.
Python program that uses empty list, None
# This is an empty list of length 0.
values = []
print(len(values))
# This is a nonexistent (None) list, with no length.
values = None
print(len(values))
Output
0
Traceback (most recent call last):
File "...", line 8, in <module>
print(len(values))
TypeError: 'NoneType' has no length
Python program that uses not, None
value = "gerbil"
if not value:
print("A") # Not reached.
value = None
if not value:
print("B") # "Not" matches None value.
Output
B
Tip: None is a good way for a method to indicate "no answer" was found. This matches the design of dictionary get() as well.
Python program that uses def, returns None
def find(n):
# This returns a value only if n equals 2.
# ... Otherwise it returns None.
if n == 2:
return 1
# The method returns None.
result = find(3)
print(result)
Output
None