You don't need "math" brackets -- just use nested parentheses. Humans use [] in writing out complex math expressions to make them more readable to other humans, but this isn't necessary. They don't mean anything different than regular parentheses. So, when writing code, just stick to the parentheses.
Answer from PurpleVermont on Stack OverflowI am refreshing python skills after some time, I am getting confused when to use diff types of brackets, round, curly, or square
Any advice or tips on how to memorize or understand this?
Thanks
Different meanings of brackets in Python - Stack Overflow
Meaning of square brackets
Add curly brackets to python please
Bython: Python with braces. Because Python is awesome, but whitespace is awful
Videos
You don't need "math" brackets -- just use nested parentheses. Humans use [] in writing out complex math expressions to make them more readable to other humans, but this isn't necessary. They don't mean anything different than regular parentheses. So, when writing code, just stick to the parentheses.
They don't work as grouping constructs - only parentheses will do that.
Square brackets define a list.
Curly brackets define either a set or a dictionary (if the elements appear as key: value).
Further to this, the extra level of clarity when dealing with multiple nestings is unnecessary, as most good IDEs will let you know when the parentheses count is imbalanced (and, you will also notice when the count is imbalanced from repetition).
Square brackets: []
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'
Parentheses: () (AKA "round brackets")
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)
- Although tuples can be created without parentheses:
- Order of operations:
(n-1)**2 - Generator expressions:
(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))
- with a generator expression:
Curly braces: {}
Dictionaries and sets, as well as in string formatting
- Dicts:
{},{0: 10},{i: i**2 for i in range(5)} - Sets:
{0},{i**2 for i in range(5)}- Except the empty set:
set()
- Except the empty set:
- In string formatting to indicate replacement fields:
- F-strings:
f'{foobar}' - Format strings:
'{}'.format(foobar)
- F-strings:
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.)
In addition to Maltysen's answer and for future readers: you can define the () and [] operators in a class, by defining the methods:
__call__(self[, args...])for()__getitem__(self, key)for[]
An example is numpy.mgrid[...]. In this way you can define it on your custom-made objects for any purpose you like.
"Curly Braces" are used in Python to define a dictionary. A dictionary is a data structure that maps one value to another - kind of like how an English dictionary maps a word to its definition.
Python:
dict = {
"a" : "Apple",
"b" : "Banana",
}
They are also used to format strings, instead of the old C style using %, like:
ds = ['a', 'b', 'c', 'd']
x = ['has_{} 1'.format(d) for d in ds]
print x
['has_a 1', 'has_b 1', 'has_c 1', 'has_d 1']
They are not used to denote code blocks as they are in many "C-like" languages.
C:
if (condition) {
// do this
}
Update: In addition to Python's dict data types Python has (since Python 2.7) set as well, which uses curly braces too and are declared as follows:
my_set = {1, 2, 3, 4}
In Python, curly braces are used to define a dictionary.
a={'one':1, 'two':2, 'three':3}
a['one']=1
a['three']=3
In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.
for entry in entries:
code....
There's a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.
from __future__ import braces