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).

Introduction

The len() function in Python is a built-in function that returns the number of items (length) in an object. The object can be a sequence (like a string, list, tuple) or a collection (like a dictionary or set).

Example

Return the the number of items of an object:

len('hello')
len(['cat', 3, 'dog'])
5
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!")

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