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]
Answer from jterrace on Stack OverflowVideos
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]
One interesting difference :
lst=[1]
print lst // prints [1]
print type(lst) // prints <type 'list'>
notATuple=(1)
print notATuple // prints 1
print type(notATuple) // prints <type 'int'>
^^ instead of tuple(expected)
A comma must be included in a tuple even if it contains only a single value. e.g. (1,) instead of (1).
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.
I'm not quite sure which belongs to which.
Clearly, I'm very new to python and programming in general. I took a programming class in high school but the focus was on making the code work, not understanding it.
Is there a general rule of thumb I haven't come across yet?
Here's a flowchart:
Is it a list? Then use brackets.
Is it a dict? Then use braces.
Otherwise, you probably want parentheses.
Probably the thing that is giving you the most confusion is tuple vs. list. The two are similar and can be used interchangeably in many circumstances. But the difference is that you can't add or remove elements from a tuple once you've built it.
http://docs.python.org/tutorial/datastructures.html
Not sure what you are really asking though. I would read through something like one of the books listed to the right of this page where it says Online books. Learn Python the Hard Way is pretty short and should help a lot with getting the basics down.
I'm working through challenges on edabit and it seems a lot of these I can't figure out because I don't fully understand the syntax of built in functions. A lot of these will output an error if parentheses are used in a certain area, but will work perfectly if brackets are used. But I don't understand how/when to know that brackets are correct?
example:
def name_shuffle(name):
first, last = name.split()
return ' '.join([last,first])
print(name_shuffle('John Smith'))I don't know why brackets need to be used in line 3. A lot of other functions seem to utilize brackets as well in situations like this.
For instance why do we use [] for slice but () for sorted? both are built-in functions for iterables.
s = 'this string.' print(s[slice(0,4)]) numbers = [2, 5, 6] print(sorted(numbers))