38

I am curious, what do the 3 different brackets mean in Python programming? Not sure if I'm correct about this, but please correct me if I'm wrong:

  • [] - Normally used for dictionaries, list items
  • () - Used to identify params
  • {} - I have no idea what this does...

Or if these brackets can be used for other purposes, any advice is welcomed! Thanks!

wjandrea
  • 23,210
  • 7
  • 49
  • 68
jake wong
  • 4,374
  • 10
  • 37
  • 75

3 Answers3

59

[]: Lists and indexing/lookup/slicing

  • Lists: [], [1, 2, 3], [i**2 for i in range(5)]
  • Indexing: 'abc'[0]'a'
  • Lookup: {0: 10}[0]10
  • Slicing: 'abc'[:2]'ab'

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

  • Tuples: (), (1, 2, 3)
    • Although tuples can be created without parentheses: t = 1, 2(1, 2)
  • Order of operations: (n-1)**2
  • Generator expression: (i**2 for i in range(5))
  • Function or method calls: print(), int(), range(5), '1 2'.split(' ')
    • with a generator expression: sum(i**2 for i in range(5))

{}: Dictionaries and sets, as well as string formatting

  • Dicts: {}, {0: 10}, {i: i**2 for i in range(5)}
  • Sets: {0}, {i**2 for i in range(5)}
  • Inside f-strings and format strings, to indicate replacement fields: f'{foobar}' and '{}'.format(foobar)

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.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
Maltysen
  • 1,718
  • 15
  • 17
2

() parentheses are used for order of operations, or order of evaluation, and are referred to as tuples. [] brackets are used for lists. List contents can be changed, unlike tuple content. {} are used to define a dictionary in a "list" called a literal.

Rampant
  • 167
  • 1
  • 1
  • 12
  • *"parentheses ... are referred to as tuples"* -- Totally incorrect. Parentheses have a much broader purpose than just for tuples (e.g. calls like `print()`), and tuples can be defined without parentheses (e.g. `t = 1, 2`). – wjandrea Dec 03 '21 at 19:37
  • *'{} are used to define a dictionary in a "list" called a literal.'* -- No, [literals](https://docs.python.org/3/reference/expressions.html#literals) are immutable by definition, therefore not including dicts, which are mutable. You might be thinking of [displays](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries), which includes "lists" and comprehensions. – wjandrea Dec 03 '21 at 19:41
2

In addition to Maltysen's answer and for future readers: you can define the () and [] operators in a class, by defining the methods:

An example is numpy.mgrid[...]. In this way you can define it on your custom-made objects for any purpose you like.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
ttq
  • 328
  • 1
  • 6