Time Complexity of Basic functions in Python

When working on programs that deal with large amounts of data, optimization becomes very important. The slightest change in the implementation of any workflow could drastically affect the time required by the program. To calculate the time taken to run a program, we need to know the time complexity of algorithms and functions that we are using in the program.

 Here let's have a look at the time complexities of some commonly used functions in Python which are li
  1. sort()
  2. 'in' or 'obj.__contains__(ele)
  3. Retrieving an element present at a given index.

Time Complexity of Sort() function:

Python implements Timsort in its sort() function. Timsort is a hybrid of Insertion Sort and Merge sort which proves to be more efficient in real-life scenarios. It basically utilizes the efficiency of Insertion sort on smaller lists by
  1. Breaking down a huge list into smaller parts 
  2. Performing Insertion sort on the smaller parts and
  3. Performing merge sort on those sorted parts.
This method is very efficient that traditional Merge sort or Insertion Sort.
Worst Case Time Complexity: O(n log n) Case Average Case Time Complexity: O(n log n) 
Best Case Time Complexity: O(n)
Space Complexity: n

Time Complexity of 'in' keyword:

The 'in' keyword is used to tell if a given element is present in a list/tuple/set or any iterable and to traverse along an iterable. Using this keyword is essentially calling l.__contains__(ele), where 'l' is the object of an iterable class and 'ele; is the element we are looking for. 

The complexity of the keyword(or function) is entirely dependent on the iterable or the object on which the operation. Let us have a look at the time complexities of preforming this operation on different iterables/objects.

List: 
    Average Case - O(1)

Set:
    Average Case - O(1)
    Worst Case - O(n)

Dict:
     Average Case - O(1)
     Worst Case - O(n)
      
You can see the complete list of time complexities of different functions here.  

Retrieving an element present at a given index:

Just like searching, retrieving an element from a given index is dependent on the iterable from which we are retrieving the element.

Retrieving an element from a list at a given index can be done at O(1) in all cases. This is contrary to popular belief which states that the time required to retrieve an element increases as the element goes deeper into the list. This is because the Implementation of Lists in Python is done as dynamic arrays instead of standard linked lists. This allows us to retrieve elements from lists from any given index at O(1) complexity.
The time complexity of accessing elements at a given index for Sets and Dictionaries are O(1) as well.



Comments

Popular posts from this blog

Variables in Python

Lists in Python