Parentheses, Square Brackets and Curly Braces in Python


Introduction

Understanding the distinct roles of parentheses, square brackets, and curly braces is crucial for proper syntax and functionality in Python code.

Generally, parentheses () are used for grouping expressions, defining functions or passing arguments, and defining tuples. Square brackets [] are used for creating lists, indexing elements and slicing snippets. Curly braces {} serve two main purposes: defining sets (unordered collections of unique elements) and dictionaries (key-value pairs).

Parentheses ()

  1. Grouping Expressions
    Parentheses () is often used to explicitly define the order of operations, where expressions within parentheses are evaluated first.
    Below is an example of how adding parentheses changes the result of an arithmetic operation and a logic expression.
print(3 + 4 * 10) 
print((3 + 4) * 10) 
print(3 + (4 * 10))

43
70
43

Arithmetic Expression Example
result1 = True or False and False
print("Result without parentheses:", result1)
result2 = (True or False) and False
print("Result with parentheses:", result2)

Result without parentheses: True
Result with parentheses: False

Logic Expression Example
  1. Defining and Calling Functions
    To define a function in Python, the keyword def is used, followed by the function name and a pair of round brackets or parentheses. These parentheses serve to declare input parameters for the function.
def greet(name): # Defining a function called hello with data being the parameters
    print("Hello " + name)
greet("World") # Call the function passing "World" as the argument 

Hello World

Defining and Calling Functions
  1. Defining a Tuple
    A tuple in Python is an ordered and immutable collection of elements, defined by enclosing values within parentheses. The elements in a tuple follows certain sequence while modifications such as appending, removal, alteration are not allowed. Moreover, it may contain heterogeneous elements, allowing for elements of different data types.Tuples are advantageous when a fixed and unchangeable sequence of elements is needed.
my_tuple = (1, 'hello', 3.14)
Defining a tuple

Square Brackets []

  1. Creating Lists
    Square brackets can be used to create a list, an ordered and mutable collection of elements.
empty = [] # Create an Empty list
data = [1, 2, 3] # Create an initialized list
List creation
  1. Indexing Elements and Slicing Snippets
    To retrieve an element from a collection such as a list or dictionary, square brackets [] are used.
my_list = ["apple", "banana", "orange"]
my_dictionary = {"Id": 1, "Name": "Alice", "City": "Champaign"}
my_tuple = (1, 'hello', 3.14)

print(my_list[1]) # return the 1st index of list
print(my_dictionary["City"]) # index the key and returns the value
print(my_tuple[1])
banana 
Champaign 
hello
Indexing a certain element
ls = [0, 1, 2, 3, 4, 5]
print(ls[:])    
print(ls[1:3])  
[0, 1, 2, 3, 4, 5]
[1, 2]
Getting a Snippet of Code
3. Selection in Dataframe

Square brackets are helpful in selecting out specific rows or columns from a dataframe.

import pandas as pd
# Creates a DataFrame with 'state', 'valuation', and 'championships' columns:
df = pd.DataFrame([
  {'team': 'Chicago Bulls', 'state': 'Illinois', 'championships': 6},
  {'team': 'Golden State Warriors', 'state': 'California', 'championships': 6},
  {'team': 'Los Angeles Lakers', 'state': 'California', 'championships': 17}, 
  {'team': 'Boston Celtics', 'state': 'Massachusetts', 'championships': 17}, 
  {'team': 'Miami Heat', 'state': 'Florida', 'championships': 3}
])
df
teamstatechampionships
Chicago BullsIllinois6
Golden State WarriorsCalifornia6
Los Angeles LakersCalifornia17
Boston CelticsMassachusetts17
Miami HeatFlorida3
Dataframe selection
df[["team"]]
team
Chicago Bulls
Golden State Warriors
Los Angeles Lakers
Boston Celtics
Miami Heat
Access a Column of the Dataframe
df[["team", "state"]]
teamstate
Chicago BullsIllinois
Golden State WarriorsCalifornia
Los Angeles LakersCalifornia
Boston CelticsMassachusetts
Miami HeatFlorida
Access multiple columns of dataframe

Square brackets can be used to select out certain rows.

df[df["championships"] > 10]
teamstatechampionships
Los Angeles LakersCalifornia17
Boston CelticsMassachusetts17
Dataframe selection

Curly Braces {}

1.Creating Dictionaries
Curly Braces {} are often used in dictionary creation. A dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and it is associated with a specific value. Dictionaries provide a flexible and efficient way to store and retrieve data using meaningful identifiers.

empty = {} # Empty Dictionary


data = {"Id": 1, "Name": "Alice", "City": "Champaign"} # keys: "Id", "Name", "City"; Values: 1, "Alice", "Champaign"
print(data)
{"Id": 1, "Name": "Alice", "City": "Champaign"}
Creating dictionary
  1. Creating Sets
    Curly braces {} can also be used to define sets, which are unordered collections of unique elements. Sets are distinct from lists or tuples as they do not allow duplicate values. Sets support various mathematical operations like union, intersection, and difference, making them useful for tasks involving distinct elements and set operations in Python.
# Creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Displaying sets
print("Set 1:", set1)
print("Set 2:", set2)
# Set operations
union_set = set1 | set2  # Union
intersection_set = set1 & set2  # Intersection
difference_set = set1 - set2  # Difference
# Displaying set operations
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Difference:", difference_set)
Set 1: {1, 2, 3, 4, 5}
Set 2: {3, 4, 5, 6, 7}
Union: {1, 2, 3, 4, 5, 6, 7}
Intersection: {3, 4, 5}
Difference: {1, 2}
Creating set