Different meanings of brackets in Python
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.)
What is the meaning of curly braces?
"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, when to use a square or round brackets?
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!
What is the difference between curly brace and square bracket in Python?
Curly braces create dictionaries or sets. Square brackets create lists.
They are called literals; a set literal:
aset = {'foo', 'bar'}
or a dictionary literal:
adict = {'foo': 42, 'bar': 81}
empty_dict = {}
or a list literal:
alist = ['foo', 'bar', 'bar']
empty_list = []
To create an empty set, you can only use set()
.
Sets are collections of unique elements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.
There is also the tuple
type, using a comma for 1 or more elements, with parenthesis being optional in many contexts:
atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')
Note the comma in the another_tuple
definition; it is that comma that makes it a tuple
, not the parenthesis. WARNING_not_a_tuple
is not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.
See the data structures chapter of the Python tutorial for more details; lists are introduced in the introduction chapter.
Literals for containers such as these are also called displays and the syntax allows for procedural creation of the contents based of looping, called comprehensions.
What does this square bracket and parenthesis bracket notation mean [first1,last1)?
A bracket - [
or ]
- means that end of the range is inclusive -- it includes the element listed. A parenthesis - (
or )
- means that end is exclusive and doesn't contain the listed element. So for [first1, last1)
, the range starts with first1
(and includes it), but ends just before last1
.
Assuming integers:
- (0, 5) = 1, 2, 3, 4
- (0, 5] = 1, 2, 3, 4, 5
- [0, 5) = 0, 1, 2, 3, 4
- [0, 5] = 0, 1, 2, 3, 4, 5
single vs double square brackets in python
The list inside a list is called a nested list. In the following list my_movies_1
, you have length 1 for my_movies_1
and the length of the inner list is 9. This inner list is accessed using my_movies_1[0]
.
my_movies_1 = [['How I Met your Mother', 'Friends', 'sillicon valley','The Wire','breakin bad', 'Family Guy','Game of Throne','South park', 'Rick and Morty']]
On the other hand, the following list is not a nested list and has a length of 9
my_movies_2 = ['How I Met your Mother', 'Friends', 'sillicon valley','The Wire','breakin bad','Family Guy','Game of Throne','South park', 'Rick and Morty']
How are they related:
Here my_movies_1[0]
would give you my_movies_2
What do [] brackets in a for loop in python mean?
The "brackets" in your example constructs a new list from an old one, this is called list comprehension.
The basic idea with [f(x) for x in xs if condition]
is:
def list_comprehension(xs):
result = []
for x in xs:
if condition:
result.append(f(x))
return result
The f(x)
can be any expression, containing x
or not.
What's the difference between lists enclosed by square brackets and parentheses in Python?
Square brackets are lists while parentheses are tuples.
A list is mutable, meaning you can change its contents:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
while tuples are not:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Note that, as many people have pointed out, you can add tuples together. For example:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
Whereas, if you were to construct this same example with a list, y
would also be updated:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
What do square brackets, [], mean in function/class documentation?
The square brackets indicate that these arguments are optional. You can leave them out.
So, in this case you are only required to pass the csvfile
argument to csv.DictReader
. If you would pass a second parameter, it would be interpreted as the fieldnames
arguments. The third would be restkey
, etc.
If you only want to specify e.g. cvsfile
and dialect
, then you'll have to name the keyword argument explicitly, like so:
csv.DictReader(file('test.csv'), dialect='excel_tab')
For more on keyword arguments, see section 4.7.2 of the tutorial at python.org.
Related Topics
Convert Timedelta to Total Seconds
How to Convert a Python Datetime.Datetime to Excel Serial Date Number
Opencv - Apply Mask to a Color Image
How to Initialize Weights in Pytorch
Python - Passing a Function into Another Function
Pygame How to Let Balls Collide
What's the Difference Between "Update" and "Update_Idletasks"
Python 2.X - Write Binary Output to Stdout
How to Redirect the Output of Print to a Txt File
Plotting Networkx Graph with Node Labels Defaulting to Node Name
How to Call Function That Takes an Argument in a Django Template
Why Return Notimplemented Instead of Raising Notimplementederror
Display the Output of the Program on Gui with Tkinter
How to Escape Latex Code Received Through User Input
How to Pass an Argument to Event Handler in Tkinter