Hướng dẫn python parentheses vs brackets

Square brackets are lists while parentheses are tuples.

Nội dung chính

  • Introduction
  • Parentheses()
  • Brackets []
  • curly braces{}
  • Table of Contents
  • Standard Parentheses - ( )
  • Invoking Functions
  • Creating Instances
  • Square brackets - [ ]
  • List Comprehensions
  • Retrieving Items from Collections
  • Curly braces - { }
  • Dictionaries
  • Formatting Strings
  • What is the difference between parentheses brackets and braces?
  • What do {} brackets mean in Python?
  • What are {} used for in Python?
  • What is the difference between curly brackets and square brackets in Python?

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]

Introduction

There are three most common parentheses in the Python language, namely: parentheses (), square brackets [], curly brackets {}; their functions are also different, and they are used to represent different Python basic built-in data types.

Parentheses()

Parentheses () in Python:
represent the tuple meta-ancestor data type, which is an immutable sequence.

Example

>>> a = (12,23) >>> a (12, 23) >>> () #空元祖 () >>> 1, #The ancestor of a value (1,)

Brackets []

The brackets [] in Python:
represent the list data type, and the list is a variable sequence.

Example

>>> list('home') ['h', 'o', 'm', 'e']

curly braces{}

The curly braces {} in Python:
represent the dict dictionary data type. The dictionary is the only built-in mapping type in Python. The values ​​in the dictionary have no special order, but they are all stored under a specific key. The keys can be numbers, strings, and ancestors.

Example

>>> dic = {'jay':'boy','may"':'girl'} >>> dic {'jay': 'boy', 'may': 'girl'}

In this article, I'll cover what standard parentheses, square brackets, and curly braces represent to Python when it interprets the code you've written. Mastering how parentheses work in Python will make it easier for you to learn to code faster and with fewer frustrating moments.

Table of Contents

  • Standard Parentheses - ( )
    • Invoking Functions
    • Creating Instances
    • Generators
  • Square brackets - [ ]
    • Lists
    • List Comprehensions
    • Retrieving Items from Collections
  • Curly braces - { }
    • Dictionaries
    • Sets
    • Formatting Strings

Beginner programmers tend to gloss over the key detail of what type of parentheses they should use when learning Python. Beginners usually focus on other aspects of programming in the excitement of learning something new, and don't think about the necessity of what type of parentheses they actually need in their code until they're used incorrectly and Python throws a syntax error. That’s why it's important to understand what each type of parentheses in Python represents and how to use each type of parentheses correctly in your Python code.

In this article, we'll cover what standard parentheses, square brackets, and curly braces represent to Python when it interprets the code you've written. Knowing these basic facts can help you choose the right type of parentheses when you start working on something new. Parentheses used incorrectly are the leading cause of syntax errors for beginners in their Python code, so mastering how parentheses work in Python will also make it easier for you to learn to code faster and with fewer frustrating moments.

  • 6 Ways to Learn Programming Faster

Standard Parentheses - ( )

Aside from defining the order of operations in mathematical and boolean operations, standard parentheses are commonly used for a few different things:

• Invoking functions

• Creating instances of a class or instances of an object

• Generators

  • Intro to Programming: What Are Booleans, Comparison Operators, and Logical Operators in Python?

Broadly speaking, the primary use of parentheses in Python is to call an object. That is the reason why standard parentheses are sometimes called the "call operator." Aside from their main use, parentheses are also used to define generator expressions. The biggest misconception about standard parentheses is that they're necessary to create a tuple. Although you will often see people use parentheses when defining tuples, they are not necessary for the process of tuple creation.

  • Intro to Programming: What Are Tuples in Python?

Here is an example of the call operator in Jupyter notebook:

Invoking Functions

Parentheses are necessary when you want to invoke functions. Calling on the name of a function without following it by parentheses will point towards the function object, but will not call the function itself. The code inside the body of the function will not get executed. 

Example function in Jupyter notebook:

Output shown in Jupyter notebook:

Hướng dẫn python parentheses vs brackets

  • How to Write and Run Code in Jupyter Notebook

Creating Instances

Instance creation is the process of creating new objects from classes. In Python, all built-in data types have their instance creation methods, but if you want to create a custom object, you need to create a custom class. 

Here is an example of creating objects of in-built data types in Jupyter notebook:

Here is an example of creating custom objects in Jupyter notebook:

Generators

Generators are a special kind of iterator that you use to avoid loading all elements of some of your data into memory. Using generators, you can render elements one-by-one. Generators are defined similarly to a function, with the addition of the yield keyword which prompts the construction of the next element. Typically, you define generators by creating an expression very similar to that of a list comprehension. The difference is that a generator is defined using parentheses, while list comprehensions are defined using square brackets.

Example of generators in Jupyter notebook: 

Square brackets - [ ]

Square brackets are commonly used in Python for: 

• Lists 

• Retrieving items from collections

Lists

Lists, as mutable collections, are one of the basic data types inside Python. You use square brackets to create lists for both empty lists and those that have items inside them.

 Example of lists in Jupyter notebook: 

  • Intro to Programming: What Are Lists in Python?

List Comprehensions

Put in simple terms, list comprehensions are an easy and elegant way of creating new lists from existing lists and are usually used to replace loops. An example of using a loop and a list comprehension to achieve the same result.

A loop in Jupyter notebook:

List comprehension example in Jupyter notebook:

Retrieving Items from Collections

Square brackets are also used to retrieve single items or multiple items from collections. When you want to retrieve a single item from a collection, you just need to specify the index of that item, or the key in case you are working with dictionaries, inside square brackets. 

Under the hood, square brackets invoke the __getitem__ method. Here's how to access single items from the following string, list, and dictionary.

Retrieving items in Jupyter notebook: 

Accessing the third character from the string in Jupyter notebook:

Accessing the first item from the list in Jupyter notebook:

Accessing the value from the dictionary defined by the key "Sandra" in Jupyter notebook:

As you can see, using square brackets is a more elegant way of accessing items than using __getitem__. Therefore, it is best to avoid using __getitem__ for retrieving items. That doesn't mean that __getitem__ doesn't have its place, on the contrary, you'll often use it when writing custom classes. In custom classes, you need to define __getitem__ as a method if you want to access elements of the object created by the custom class using square brackets.

You can also use square brackets to retrieve so-called slices of data. Slices are retrieved very similarly to single items. The only difference is that you don't specify an index inside the square brackets, but you instead specify a range of indexes. This allows you to access a part of some collection of items easily.

The standard formulation when using square brackets to retrieve a slice of data is [start:end:step]. The step part is often omitted when wanting to retrieve a whole subset of a collection. When skipped, the step variable defaults to one. Here's how you can retrieve a slice of data:

Here's some example data I've created in Jupyter notebook:

Now, access all items between 10 and 18 (including 10 and 18), skipping every second item:

It is important to mention that there is essentially no difference between retrieving a single item and retrieving a slice. Both processes use __getitem__ in the background.

Also, slices are treated by Python as classes, which means that you can achieve the same result I achieved with the code above by writing the following line of code in Jupyter notebook:

Curly braces - { }

One of the biggest differences between Python and other popular programming languages is that in Python, curly braces are not used to create program blocks for flow control. In Python, indentation is used for flow control, which makes Python much easier to read than most other programming languages.

That being said, curly braces do have their uses in Python. Curly braces are commonly used to:

• Create dictionaries

• Create sets

• Format strings

Dictionaries

Dictionaries are created in Python using curly braces. You can use curly braces to create both empty dictionaries and dictionaries that contain key-value pairs. 

Example of curly braces to create dictionaries in Jupyter notebook:

Of course, you can always create dictionaries using the dict() method, but that way of creating dictionaries is not used very often. Using curly braces is also faster than invoking dict(), because curly braces are a part of Python's syntax and do not require a function call.

Similarly to how you can use list comprehensions and square brackets to create lists, you can use curly braces and dict comprehensions to create dictionaries. 

Here's an example of creating dictionaries with curly brackets in Juptyer notebook:

  • Intro to Programming: What Are Dictionaries in Python?

Sets

Sets are collections of mutable, unique, hashable values. When working with sets, you can treat them as dictionaries that contain only keys and no values. They are not used as often as dictionaries and are usually used as an easy way to remove duplicates from a collection. A set is created by entering values instead of pairs inside curly braces.  

An example of creating sets in Juptyer notebook:

However, creating empty sets is not done by using curly braces. If you try to just leave nothing between the curly braces, Python will automatically create a dictionary. Therefore, to create an empty set you must invoke set()

Example of a set() in Juptyer notebook:

Formatting Strings

The standard way to format strings in Python is to use a combination of curly braces and standard parenthesis, by inserting empty curly braces in the place where you want to add something to a string.

Example of formatting strings in Jupyter notebook: 

Of course, the same can be done using variables:

We can also format strings by using keyword arguments:

  • Intro to Programming: What Are Different Data Types in Programming?

However, as of Python 3.6, an alternative and more elegant way of formatting strings was introduced using f-strings. By using f-strings, you can completely avoid using standard parentheses and instead use only curly braces. You just need to add an f before the string to signal to Python that you are going to use that new functionality to format strings. 

Using f-strings is much simpler, as show in this example in Jupyter notebook:

As you can see, using f-strings, you can directly insert variables inside curly braces. This gives you an easy way to precisely assign variable values to certain spots in a string, and even to manipulate those same values. 

Example of assigning variable values using f-strings in Jupyter notebook: 

In this article, I've demonstrated some of the different uses for standard parentheses, square brackets, and curly braces in Python that you can use as a cheat sheet. 

What is the difference between parentheses brackets and braces?

Parentheses, brackets, and braces are ways of separating parts of a mathematical expression from one another, and they all look quite similar. Parentheses are smooth and curved ( ), brackets are square [ ], and braces are curly { }. In mathematics, they are mostly used for order of operations.

What do {} brackets mean in Python?

[] brackets are used for lists. List contents can be changed, unlike tuple content. {} are used to define a dictionary in a "list" called a literal.

What are {} used for in Python?

In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

What is the difference between curly brackets and square brackets in Python?

Curly braces create dictionaries or sets. Square brackets create lists. To create an empty set, you can only use set() . Sets are collections of unique elements and you cannot order them.