Python Basics — List Methods
List Methods
Python lists come with powerful built-in methods for adding, removing, sorting, and searching.
Adding Elements
append() — Add to End
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # ['apple', 'banana', 'cherry']
extend() — Add Multiple Elements
fruits = ["apple", "banana"]
fruits.extend(["cherry", "date"])
print(fruits) # ['apple', 'banana', 'cherry', 'date']
# extend() vs append() with a list
fruits = ["apple"]
fruits.append(["b", "c"]) # Adds the list as ONE element
print(fruits) # ['apple', ['b', 'c']]
fruits = ["apple"]
fruits.extend(["b", "c"]) # Adds each element individually
print(fruits) # ['apple', 'b', 'c']
insert() — Add at Position
fruits = ["apple", "cherry"]
fruits.insert(1, "banana") # Insert at index 1
print(fruits) # ['apple', 'banana', 'cherry']
fruits.insert(0, "avocado") # Insert at beginning
print(fruits) # ['avocado', 'apple', 'banana', 'cherry']
Removing Elements
remove() — Remove by Value
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana") # Removes FIRST occurrence
print(fruits) # ['apple', 'cherry', 'banana']
# ValueError if not found
# fruits.remove("grape") # ValueError
pop() — Remove by Index
fruits = ["apple", "banana", "cherry"]
last = fruits.pop() # Remove and return last item
print(last) # cherry
print(fruits) # ['apple', 'banana']
first = fruits.pop(0) # Remove and return item at index 0
print(first) # apple
print(fruits) # ['banana']
clear() — Remove All
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits) # []
del — Delete by Index or Slice
fruits = ["apple", "banana", "cherry", "date"]
del fruits[1] # Delete index 1
print(fruits) # ['apple', 'cherry', 'date']
del fruits[0:2] # Delete slice
print(fruits) # ['date']
Sorting
sort() — Sort In Place
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True)
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# Sort strings (case-sensitive by default)
words = ["banana", "Apple", "cherry"]
words.sort()
print(words) # ['Apple', 'banana', 'cherry']
# Case-insensitive sort
words.sort(key=str.lower)
print(words) # ['Apple', 'banana', 'cherry']
sorted() — Return New Sorted List
numbers = [3, 1, 4, 1, 5]
sorted_nums = sorted(numbers)
print(sorted_nums) # [1, 1, 3, 4, 5]
print(numbers) # [3, 1, 4, 1, 5] (original unchanged)
sort() vs sorted()
| Feature | list.sort() |
sorted(list) |
|---|---|---|
| Returns | None |
New sorted list |
| Modifies original | Yes | No |
| Works on | Lists only | Any iterable |
reverse() — Reverse In Place
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) # ['cherry', 'banana', 'apple']
Searching
index() — Find Position
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.index("banana")) # 1 (first occurrence)
print(fruits.index("banana", 2)) # 3 (search from index 2)
# ValueError if not found
# fruits.index("grape") # ValueError
count() — Count Occurrences
numbers = [1, 2, 3, 2, 2, 4, 2]
print(numbers.count(2)) # 4
print(numbers.count(5)) # 0
Copying Lists
Shallow Copy
original = [1, 2, 3]
# Three ways to copy
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)
copy1.append(4)
print(original) # [1, 2, 3] (not affected)
print(copy1) # [1, 2, 3, 4]
Assignment Is NOT Copying
original = [1, 2, 3]
alias = original # Both point to the SAME list
alias.append(4)
print(original) # [1, 2, 3, 4] — original also changed!
List as Stack and Queue
Stack (LIFO — Last In, First Out)
stack = []
stack.append("first")
stack.append("second")
stack.append("third")
print(stack.pop()) # third
print(stack.pop()) # second
print(stack) # ['first']
Queue (FIFO — First In, First Out)
from collections import deque
queue = deque()
queue.append("first")
queue.append("second")
queue.append("third")
print(queue.popleft()) # first
print(queue.popleft()) # second
print(queue) # deque(['third'])
Use
collections.dequefor queues —list.pop(0)is slow (O(n)) because it shifts all elements.
Complete Methods Reference
| Method | Description | Returns |
|---|---|---|
append(x) |
Add to end | None |
extend(iter) |
Add all from iterable | None |
insert(i, x) |
Insert at position | None |
remove(x) |
Remove first occurrence | None |
pop(i) |
Remove and return at index | Removed item |
clear() |
Remove all items | None |
sort() |
Sort in place | None |
reverse() |
Reverse in place | None |
copy() |
Shallow copy | New list |
index(x) |
Find first index of x | Index |
count(x) |
Count occurrences of x | Count |
Summary
- Add:
append(),extend(),insert() - Remove:
remove(),pop(),clear(),del - Sort:
sort()(in-place),sorted()(new list) - Search:
index(),count() - Copy:
.copy(),[:], orlist() sort()andreverse()modify the list and returnNone- Assignment (
=) creates an alias, not a copy
Next up: List Slicing →