The built-in len()
function returns the number of items in an object, such as sequences or collections. It’s useful for determining the size of data structures:
len()
Signature Arguments Argument Description obj
An object that supports length Return Value
len()
Examples
With a string as an argument:
With lists and tuples as an argument:
With dictionaries and sets as arguments:
len()
Common Use Cases
The most common use cases for the len()
function include:
len()
to 0
.len()
Real-World Example
You can use len()
to validate user input, such as ensuring a username is within a certain length:
In this example, you use len()
to check whether the entered username meets the required length criteria, ensuring valid input.
len()
in Custom Classes
You can support len()
in your custom classes by implementing the .__len__()
special method. Here’s an example:
By implementing .__len__()
, you enable your custom class to work seamlessly with the len()
function, providing a way to determine the number of items it contains.
Tutorial
Using the len() Function in PythonIn this tutorial, you'll learn how and when to use the len() Python function. You'll also learn how to customize your class definitions so that objects of a user-defined class can be used as arguments in len().
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4