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!
[]
Lists and indexing/lookup/slicing
[]
, [1, 2, 3]
, [i**2 for i in range(5)]
'abc'[0]
→ 'a'
{0: 10}[0]
→ 10
'abc'[:2]
→ 'ab'
()
(AKA "round brackets")Tuples, order of operations, generator expressions, function calls and other syntax.
()
, (1, 2, 3)
t = 1, 2
→ (1, 2)
(n-1)**2
(i**2 for i in range(5))
print()
, int()
, range(5)
, '1 2'.split(' ')
sum(i**2 for i in range(5))
{}
Dictionaries and sets, as well as in string formatting
{}
, {0: 10}
, {i: i**2 for i in range(5)}
{0}
, {i**2 for i in range(5)}
set()
f'{foobar}'
'{}'.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.
<>
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.)