List Methods
| Method | Purpose |
|---|
append(x) | Add x to the end of the list |
extend(iterable) | Add all items from another iterable to the end |
count(x) | Count occurrences of x |
remove(x) | Remove the first occurrence of x |
index(x) | Return the index of the first occurrence of x |
pop(i) | Remove and return item at index i (default: last) |
insert(i, x) | Insert x at index i |
sort() | Sort the list in place (ascending by default) |
reverse() | Reverse the list in place |
append() vs extend()
a = [1, 2, 3]
a.append([4, 5]) # adds the WHOLE list as ONE element
print(a) # [1, 2, 3, [4, 5]]
b = [1, 2, 3]
b.extend([4, 5]) # adds EACH element individually
print(b) # [1, 2, 3, 4, 5]
count() and index()
nums = [1, 2, 2, 3, 2, 4]
print(nums.count(2)) # 3
print(nums.index(2)) # 1 (first occurrence)
remove() and pop()
fruits = ["apple", "banana", "mango", "banana"]
fruits.remove("banana") # removes first "banana" only
print(fruits) # ['apple', 'mango', 'banana']
nums = [10, 20, 30, 40]
last = nums.pop() # removes & returns last item -> 40
print(last, nums) # 40 [10, 20, 30]
second = nums.pop(1) # removes & returns index 1 -> 20
print(second, nums) # 20 [10, 30]
insert()
nums = [10, 20, 40]
nums.insert(2, 30) # insert 30 at index 2
print(nums) # [10, 20, 30, 40]
sort() and reverse()
nums = [5, 2, 8, 1, 9]
nums.sort() # ascending, in place
print(nums) # [1, 2, 5, 8, 9]
nums.sort(reverse=True) # descending
print(nums) # [9, 8, 5, 2, 1]
names = ["Riya", "amit", "Zoya", "bhanu"]
names.sort(key=str.lower) # case-insensitive sort
print(names) # ['amit', 'bhanu', 'Riya', 'Zoya']
nums.reverse() # reverse current order (not sorted!)
print(nums)
# sorted() -- returns a NEW list, does not modify original
original = [3, 1, 2]
new_list = sorted(original)
print(original, new_list) # [3, 1, 2] [1, 2, 3]
clear()
a = [1, 2, 3]
a.clear()
print(a) # []