len()

Returns the number of items in a collection, or the number of characters in a string.

Returns
An integer.
On this page

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

#

Spotted a mistake or missing an example? Write to us.