Time Complexity for Adding Element in Python Set vs List (original) (raw)

Last Updated : 19 Dec, 2024

Adding elements differs due to their distinct underlying structures and requirements for uniqueness or order. Let's explore and compare the time complexity by adding elements to lists and sets. In this article, we will explore the differences in time complexities between a Set and a List if we add an element to that.

Adding elements in Python Set

When we add an element in the set using add () method, Python computes its hash to check if it’s already in the set quickly. This allows sets to perform fast **O(1) membership checks, avoiding the need for slower searches.

Python `

a = {1, 2, 3}

Add element

a.add(4) print(a)

`

**Explanation :

**Time complexity:

Adding Elements in Python List

When we add an element to a list using the append() method, Python directly adds the element to the end. This operation has **O(1) amortized time complexity, as no hashing or duplicate checks are needed.

Python `

a = [1, 2, 3]

#Add element a.append(4) print(a)

`

**Explanation:

**Time Complexity:

Compare Time Complexity for Adding Element in Python Set vs List

Feature Python Set Python List
Average Time Complexity (Adding) O(1)( for add()) O(1) (for append())
Worst Time Complexity (Adding) O(n) (rare, due to hash collisions) O(n) (for resizing when appending)
Element Lookup O(1) (efficient) O(n) (searching through the list)
Memory Usage More memory due to hash table overhead Less memory usage for dynamic arrays

Similar Reads