What do [] brackets in a for loop in python mean?

The “brackets” in your example constructs a new list from an old one, this is called list comprehension.

The basic idea with [f(x) for x in xs if condition] is:

def list_comprehension(xs):
    result = []
    for x in xs:
        if condition:
            result.append(f(x))
    return result

The f(x) can be any expression, containing x or not.

Leave a Comment