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.)
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.
Meaning of square brackets
Add curly brackets to python please
In python, when to use a square or round brackets? - Stack Overflow
How to type bracket in python? Just hear me out okay?
Videos
I 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
They are part of the Python syntax and unlike using single (') or double (") quotes, they can pretty much never be interchanged.
Square and rounded brackets can mean so many different things in different circumstances. Just to give an example, one may think that both the following are identical:
a = [1,2,3]
a = (1,2,3)
as a[0] gives 1 in both cases. However, the first one is creating a list whereas the second is a tuple. These are different data types and not knowing the distinction can lead to difficulties.
Above is just one example where square and rounded brackets differ but there are many, many others. For example, in an expression such as:
4 * ((12 + 6) / 9)
using square brackets would lead to a syntax error as Python would think you were trying to create a nested list:
4 * [[12 + 6] / 9]
So hopefully you can see from above, that the two types of brackets do completely different things in situations which seem identical. There is no real rule of thumb for when one type does what. In general, I guess that square brackets are used mainly for lists and indexing things whereas rounded brackets are for calculations (as you would in maths) and functions etc.
Hope this helps you out a bit!
It's hard to answer succinctly, but I can give you some common examples.
Square brackets define lists:
my_list = [1, 2, 3, 4]
They are also used for indexing lists. For instance:
print(my_list[1])
Returns 2.
Additionally, they are frequently used to index dictionaries, which are defined with curly brackets:
my_dict = {5:'a', 6:'b', 7:'c'}
The indexing for dictionaries requires that I input the "key" as follows:
print(my_dict[6])
Returns b.
Functions are called using round brackets. For instance, if I want to add an element to my list, I can call the append() function:
my_list.append(8)
I have just added 8 to my list. You will notice that when I called the print function I also used curved brackets.
This is by no means comprehensive, but hopefully it will give a starting point.