Python pass statement is a no-operation statement. It’s used to create empty code blocks and empty functions.
Python pass Statement Examples
Let’s look at some examples of Python pass statements.
1. pass statement in a code block
If the number is divided by 2, then we do nothing. Else, we add it to a temporary list. Finally, return the temporary list having only odd numbers to the caller.
Python doesn’t support empty code blocks. So we can use the pass statement here for the no-operation in the if-condition block.
def remove_evens(list_numbers): list_odds =  for i in list_numbers: if i % 2 == 0: pass else: list_odds.append(i) return list_odds l_numbers = [1, 2, 3, 4, 5, 6] l_odds = remove_evens(l_numbers) print(l_odds)
Output: [1, 3, 5]
Here we don’t need any operation in the if-condition block. So we have used the pass statement for the no-operation.
2. pass statement for an empty function
Python doesn’t have the concept of abstract functions. If we have to define an empty function, we can’t write it like this.
def foo(): # TODO - implement later
Output: IndentationError: expected an indented block
We can use a pass statement to define an empty function. The function will have a statement but it won’t do anything.
def foo(): pass
Can we have multiple pass statements in a function?
Yes, we can have multiple pass statements in a function or a code block. It’s because the pass statement doesn’t terminate the function. Its only work is to provide an empty statement.
def bar(): pass print('bar') pass if True: pass pass print('True') else: print('False') pass pass
Why do we need a pass statement?
- Python pass statement is very helpful in defining an empty function or an empty code block.
- The most important use of the pass statement is to create a contract for classes and functions that we want to implement later on. For example, we can define a Python module like this:
class EmployeeDAO: def get_emp_by_id(self, i): """ TODO: implement this function later on :param i: employee id :return: employee object """ pass def delete_emp(self, i): pass # This function will read Employees CSV Data file and return list of Employees def read_csv_file(file): pass
We can proceed with the implementation. The third-party code knows the functions and methods that we will implement, so they can proceed with their implementation.