pythonbrackets

Different meanings of brackets in Python


What do the 3 different brackets mean in Python programming?

Can these brackets can be used for other purposes?


Solution

  • Square brackets: []

    Lists and indexing/lookup/slicing

    Parentheses: () (AKA "round brackets")

    Tuples, order of operations, generator expressions, function calls and other syntax.

    Curly braces: {}

    Dictionaries and sets, as well as in string formatting

    Regular expressions

    All of these brackets are also used in regex. Basically, [] are used for character classes, () for grouping, and {} for repetition. For details, see The Regular Expressions FAQ.

    Angle brackets: <>

    Used when representing certain objects like functions, classes, and class instances if the class doesn't override __repr__(), for example:

    >>> print
    <built-in function print>
    >>> zip
    <class 'zip'>
    >>> zip()
    <zip object at 0x7f95df5a7340>
    

    (Note that these aren't proper Unicode angle brackets, like ⟨⟩, but repurposed less-than and greater-than signs.)