Python’s built-in function len()
returns the length of the given string, array, list, tuple, dictionary, or any other iterable. The type of the return value is an integer that represents the number of elements in this iterable.
Usage
Learn by example! Here are some examples on how to use the len()
built-in function.
>>> friends = ['Alice', 'Bob', 'Carl', 'Ann'] >>> len(friends) 4 >>> friends.extend([1, 2, 3]) >>> len(friends) 7 >>> len('hello world') 11 >>> len('hi') 2 >>> len((1, 2, 3)) 3 >>> len({42, 21}) 2 >>> age = {'Alice': 18, 'Bob': 21} >>> len(age) 2 >>> age['Carl'] = 33 >>> len(age) 3
The examples show the len()
function applied to a list, tuple, string, dictionary, and set. Generally, you can apply it to any iterable and it returns the number of elements in this iterable.
Syntax len()
The len()
object has the following syntax:
Syntax:
len(object) # Get object's number of elements. Should be an iterable or container type.
Arguments | object | An iterable or container that contains elements. |
Return Value | integer | Returns the number of elements in the object . |
Check out my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Publisher Link: https://nostarch.com/pythononeliners
What’s the Runtime Complexity of len()?
The runtime complexity of the len()
function on your Python list is O(1). It takes constant runtime no matter how many elements are in the list. Why? Because the list object maintains an integer counter that increases and decreases as you add and remove list elements. Looking up the value of this counter takes constant time.
Python list objects keep track of their own length. When you call the function len(...)
on a list object, here’s what happens (roughly):
- The Python virtual machine looks up the
len(...)
function in a dictionary to find the associated implementation. - You pass a list object as an argument to the
len()
function so the Python virtual machine checks the__len__
method of the list object. - The method is implemented in C++ and it’s just a counter that’s increased each time you add an element to the list and decreased if you remove an element from the list. For example, say, the variable
length
stores the current length of the list. The method then returns the valueself.length
. - Done.
Implementing Custom len() Function
The len()
function is implemented for many different data types in Python. In fact, each time you implement your own object, you can define the __len__
method to enable the len()
function on your custom object as well. Naturally, the __len__
method has been implemented by practically all data types in the Python packages where it makes sense.
Specification: object.__len__(self)
The function __len__()
is called to implement the built-in function len()
described in this article. Thus, you can create your own container objects—even non-iterables that still contain values. The return value of the __len__()
custom method should be an integer greater than or equal to 0.
Note: an object that doesn’t define the __bool__()
method and that has a __len__()
method that returns zero is considered to be False in a Boolean context—for example when you use it with the built-in function bool(object)
.
You can define any positive integer return value you want. For collection types such as lists, the return value is the number of elements in the collection. Interestingly, the method also defines whether the default Boolean interpretation of the object should be True
(for a positive length >0) or False
(for a zero length == 0).
For example, consider the code if o: print('hi')
for object o
. If the length function len(o)
returns 0, the if condition won’t hold—assuming there’s no implementation of the __bool__()
method.
Here’s a full example on how you can implement your custom object and its len()
function:
class Cars: ''' The cars in your garage. ''' def __init__(self): self.cars = [] def add_car(self, car): self.cars.append(car) def __len__(self): return len(self.cars) myCars = Cars() myCars.add_car('porsche') # <-- Nah! myCars.add_car('tesla') # <-- Nah! myCars.add_car('vw') # <-- Still... Nah! print('The number of cars in my garage: ', len(myCars)) # The number of cars in my garage: 3
Note how we pass a Cars
object into the len()
function that is not an iterable but still a container for other cars. In fact, you don’t even have to create a container object to allow the len()
function on your custom object—as long as you implement the __len__()
method!
Summary
Python’s built-in function len()
returns the length of the given string, array, list, tuple, dictionary, or any other iterable.
print(len('hi')) # 2 print(len([1, 2, 3])) # 3
The type of the return value is an integer that represents the number of elements in this iterable.
print(type(len('hi'))) # <class 'int'>
I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.