C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Empty: The second len call tests an empty string. This string has zero characters but is not None.
TypeError: Len relies on the type of the variable passed to it. A NoneType has no len built-in support.
NonePython program that uses len on strings
# Has length of 3:
value = "cat"
print(len(value))
# Has length of 0:
value = ""
print(len(value))
# Causes TypeError:
value = None
print(len(value))
Output
3
0
Traceback (most recent call last):
File "C:\programs\file.py", line 13, in <module>
print(len(value))
TypeError: object of type 'NoneType' has no len()
Dictionary: For the dictionary, each pair is counted as one unit. Keys and values are not independent.
DictionaryPython program that uses len, collections
# Get length of list with len.
elements = [1, 2, 3]
print(len(elements))
# Get length of tuple.
items = ("cat", "dog", "bird", "shark")
print(len(items))
# Length of example set (key count).
set = {100, 200, 300}
print(len(set))
# Length of dictionary (pair count).
lookup = {"cat" : 4, "centipede" : 100}
print(len(lookup))
Output
3
4
3
2
So: We must do those things (recurse, loop) with custom code. We can test sub-elements and use len on them.
ListPython program that uses len on nested list
# A nested list:
list = [1, 2, [4, 5]]
# Shallow count of elements.
print(len(list))
print(len(list[2]))
Output
3
2
Note: Conceptually len() counts countable units: chars in a string, elements in a list. A number has digits, but no other "units."
NumbersPython program that causes error, len on int
value = 100
# Cannot take length of int:
length = len(value)
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 6, in <module>
length = len(value)
TypeError: object of type 'int' has no len()
Version 1: In this version of the code, we access the length of a string with len in a loop. This is timed.
Version 2: We test a for-loop version. The end result is the same (each character is counted).
Result: It is many times faster to access len. The for-loop is useful only when counting chars, where their values matter.
Python program that times len, char counting
import time
value = "characters"
print(time.time())
# Version 1: len
for i in range(0, 1000000):
length = len(value)
if length != 10:
raise Exception()
print(time.time())
# Version 2: count chars
for i in range(0, 1000000):
length = 0
for c in value:
length += 1
if length != 10:
raise Exception()
print(time.time())
Output
1406752804.325871
1406752804.606887 len = 0.281 s
1406752806.05097 for-loop = 1.444 s