Skip to content

Lists

Lists related humanization.

natural_list(items)

Natural list.

Convert a list of items into a human-readable string with commas and 'and'.

Examples:

>>> natural_list(["one", "two", "three"])
'one, two and three'
>>> natural_list(["one", "two"])
'one and two'
>>> natural_list(["one"])
'one'

Parameters:

Name Type Description Default
items list

An iterable of items.

required

Returns:

Name Type Description
str str

A string with commas and 'and' in the right places.

Source code in .tox/docs/lib/python3.13/site-packages/humanize/lists.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def natural_list(items: list[Any]) -> str:
    """Natural list.

    Convert a list of items into a human-readable string with commas and 'and'.

    Examples:
        >>> natural_list(["one", "two", "three"])
        'one, two and three'
        >>> natural_list(["one", "two"])
        'one and two'
        >>> natural_list(["one"])
        'one'

    Args:
        items (list): An iterable of items.

    Returns:
        str: A string with commas and 'and' in the right places.
    """
    if len(items) == 1:
        return str(items[0])
    elif len(items) == 2:
        return f"{str(items[0])} and {str(items[1])}"
    else:
        return ", ".join(str(item) for item in items[:-1]) + f" and {str(items[-1])}"