Topic 22 of 58
List Operations
Overview
Because lists are dynamic, Python provides built-in methods for seamlessly adding, removing, sorting, and locating elements. However, in coding interviews, understanding the Time Complexity of these operations is critical. While adding to the end of a list is fast, inserting elements at the beginning forces Python to physically shift every other element in memory, causing massive performance drops on large datasets.
Syntax
python
arr = [1, 2, 3]
# Adding Elements
arr.append(4) # Adds to end: [1, 2, 3, 4] -> O(1)
arr.insert(0, 0) # Adds to index 0: [0, 1, 2, 3, 4] -> O(N) Slow!
arr.extend([5, 6]) # Merges another iterable: [0, 1, 2, 3, 4, 5, 6]
# Removing Elements
last_val = arr.pop() # Removes and returns last item -> O(1)
first_val = arr.pop(0) # Removes and returns first item -> O(N) Slow!
arr.remove(3) # Removes first occurrence of value '3'
# Sorting
arr.sort() # Sorts the original list IN PLACE
new_sorted = sorted(arr) # Returns a brand NEW sorted listCommon Pitfalls
- Using
pop(0)orinsert(0, val)in a loop. These are O(N) operations. If you have a loop running 100,000 times, this will cause your program to freeze. Usecollections.dequeif you need a Queue. - Assuming
.sort()returns the sorted list. It returnsNonebecause it mutates the list in place.
Interview Questions
Q:
What is the difference between
append() and extend()?A:
append(val) takes whatever object you pass it and adds it as a single element at the end of the list. extend(iterable) takes an iterable (like another list) and appends each element individually.
Real-World Example
Using a list as a Stack (Last-In, First-Out).
example
python
history_stack = []
# User visits pages
history_stack.append("home_page")
history_stack.append("profile_page")
# User clicks 'Back' button
current_page = history_stack.pop()
print(f"Returned from {current_page}") # profile_pageCheck Your Knowledge
Test your understanding of List Operations with these quick questions.