0
0
Pythonprogramming~5 mins

Creating custom modules in Python - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: Creating custom modules
O(n)
Understanding Time Complexity

When we create custom modules in Python, we want to know how the time it takes to run our code changes as our program grows.

We ask: how does using a module affect the speed of our program as it gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


# custom_module.py

def greet(name):
    return f"Hello, {name}!"

# main.py
import custom_module

users = ["Alice", "Bob", "Charlie"]  # Example list of users

for user in users:
    print(custom_module.greet(user))
    

This code imports a custom module with a simple function and calls it once for each user in a list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the greet function inside a loop over the users list.
  • How many times: Once for each user in the list.
How Execution Grows With Input

Each time we add more users, the program calls the greet function more times.

Input Size (n)Approx. Operations
1010 greet calls
100100 greet calls
10001000 greet calls

Pattern observation: The number of operations grows directly with the number of users.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the number of users grows.

Common Mistake

[X] Wrong: "Importing a module makes the program slower every time I call its functions."

[OK] Correct: Importing happens once at the start; calling functions inside loops is what grows with input size.

Interview Connect

Understanding how your code runs when using modules helps you write clear and efficient programs, a skill valued in many coding challenges and real projects.

Self-Check

"What if the greet function itself had a loop over a list of greetings? How would the time complexity change?"