PythonBuilt-in functions
len()
Returns the number of items in a collection, or the number of characters in a string.
- Returns
- An integer.
Example
#Python
print(len("CodeWorlds"))
print(len([72, 95, 88]))
print(len({"html": 11, "python": 12}))
print(len(""))Resultsaved result, you can check it
10
3
2
0
Definition and usage
#The len() function returns the length of an object: the number of characters in a string, the number of items in a list, tuple, or set, and the number of keys in a dictionary.
It runs very fast, because collections in Python keep track of their own length. You don't need to worry about calling it many times.
You can check for an empty collection more briefly without len(): if not tasks: is equivalent to if len(tasks) == 0:, because an empty collection counts as false.
Syntax
#Syntax
len(object)Parameters
#object
a string or collection
The object whose length you want to know.
Good practices
#- Accented characters count as one character each:
len("café")is 4. - To check whether a list is empty,
if not my_list:is enough.
Related entries
#- range()Creates a sequence of integers, most often for a for loop.
- list()Creates a list, either empty or from the items of another iterable.
- str()Converts a value to a string.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
- Special methodsMethods with double underscores that let objects work with the ==, <, + and in operators, and with the len() function.
Spotted a mistake or missing an example? Write to us.