Kodeclik Blog
Brackets in Python
In Python, there are three types of brackets—parentheses (), square brackets [], and curly braces {}. They serve distinct purposes, each essential for different aspects of programming.
Parentheses
Parentheses () are used for grouping expressions, defining functions, and creating tuples. For example, when defining a function, parentheses are used to enclose the function's parameters. Additionally, they are crucial for maintaining the order of operations in mathematical expressions.
Here's an example of using parentheses to define a function and create a tuple:
def greet(name):
print(f"Hello, {name}!")
# Create a tuple
my_tuple = (1, 2, 3)
print(my_tuple)
The output is:
(1, 2, 3)
Square brackets
Square brackets [] are primarily used for creating lists and indexing elements in lists or dictionaries. They also allow for slicing and selecting specific rows or columns in data structures like Pandas dataframes.
For instance, you can create a list and access its elements using square brackets:
# Create a list
my_list = [1, 2, 3]
print(my_list[0])
# Accessing a DataFrame column
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df[['A']])
The output will be:
1
A
0 1
1 2
Curly Braces
Curly braces {} are used to create dictionaries and sets. Dictionaries are collections of key-value pairs, while sets are unordered collections of unique elements. Curly braces also play a role in string formatting. Here's how you can create a dictionary and a set:
# Create a dictionary
my_dict = {'name': 'John', 'age': 30}
print(my_dict['name'])
# Create a set
my_set = {1, 2, 3}
print(my_set)
The output is:
John
{1, 2, 3}
In other words, the reason you have different types of brackets in Python is because you need them for different data structures and operations. Each type of bracket helps maintain clarity and efficiency in Python code by providing specific functionalities that are not interchangeable. This distinction allows developers to write more readable and maintainable code.
Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.