Member-only story
Hi everyone, welcome back. Today, we will be going over the len() function in Python and see how it works. The len() function is a built in function and its purpose is to return the number of items that appear in a given object. Let’s get into it.
Len Function
Let’s see how the len() function works. First we will create a list and throw in some junk values. Then we will pass in the list into the len() function and print out the result. Let’s see our example:
list = [1, 2, 3]
result = len(list)
print(result)Output:
3
As we can see in the output above, our len() function has returned a 3. This is verifying that our list contains 3 different items, in which it does, meeting our expected output.
The object passed into the len() function must be a collection or a sequence of items. Let’s see what happens if we pass in an object that is not a collection or a sequence:
result = len(8)
print(result)Output:
TypeError: object of type 'int' has no len()
We get an error! Using an object that is not a collection or a sequence will not work. So don’t do it!