What You Will Learn
Beginner
- All list methods
- sort vs sorted
- In-place vs new list methods
List Methods Reference
| Method | What it does | Modifies original? |
|---|---|---|
append(x) | Add x to end | Yes |
extend(iter) | Add all items from iterable | Yes |
insert(i, x) | Insert x at index i | Yes |
remove(x) | Remove first occurrence of x | Yes |
pop(i) | Remove and return item at i (default: last) | Yes |
clear() | Remove all items | Yes |
index(x) | Find index of first x | No |
count(x) | Count occurrences of x | No |
sort() | Sort in place | Yes |
reverse() | Reverse in place | Yes |
copy() | Return a shallow copy | No |
sort() vs sorted()
Common confusion
list.sort() sorts IN PLACE and returns None. sorted(list) returns a NEW sorted list without modifying the original.Terminalpython
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# sort() - modifies original
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# sorted() - returns new list
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original) # [3, 1, 4, 1, 5] (unchanged)
print(sorted_list) # [1, 1, 3, 4, 5]
# Sort descending
numbers.sort(reverse=True)
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]Practical Exercise
Create [5, 2, 8, 1, 9, 3]
Sort with .sort() - print result
Create a new sorted copy with sorted()
Sort in reverse: .sort(reverse=True)
Count occurrences: [1,1,1,2,2].count(1)
Key Takeaways
- 11 list methods: append, extend, insert, remove, pop, clear, index, count, sort, reverse, copy.
- sort() modifies in place. sorted() returns new list.
- append() adds one item. extend() adds multiple.
- count(x) counts occurrences. index(x) finds position.
- copy() creates a shallow copy.
Comments
Comments
Post a Comment