![]() |
VOOZH | about |
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.
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.
{1, 2, 3, 4}
Explanation :
Time complexity:
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.
[1, 2, 3, 4]
Explanation:
append() method. Lists allow duplicates, so 4 will be added even if it already exists in the list.Time Complexity:
append().Feature | Python Set | Python List |
|---|---|---|
Average Time Complexity (Adding) | O(1)( for add()) | O(1) (for |
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 |