Python len() built-in function

From the Python 3 documentation

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Example

Return the the number of items of an object:

>>> len('hello')
# 5

>>> len(['cat', 3, 'dog'])
# 3

Test of emptiness

Test of emptiness

Test of emptiness of strings, lists, dictionaries, etc., should not use len, but prefer direct boolean evaluation.

>>> a = [1, 2, 3]

# bad
>>> if len(a) > 0:  # evaluates to True
...     print("the list is not empty!")
...
# the list is not empty!

# good
>>> if a: # evaluates to True
...     print("the list is not empty!")
...
# the list is not empty!

Subscribe to pythoncheatsheet.org

A bullshit free publication, full of interesting, relevant links.