📌 Good for: Ordered collection, allows duplicates, mutable
Introduction
Lists are one of the most commonly used data structures in Python. They allow storing multiple items in a single variable, and they are mutable, meaning their content can be modified. Lists support various operations, including adding, removing, sorting, and slicing elements.
Basic Operations
list.append(x) → Add an item to the end
my_list = [1, 2, 3]
my_list.append(4)
# Output: [1, 2, 3, 4]
list.extend(iterable) → Add multiple items
my_list.extend([5, 6])
# Output: [1, 2, 3, 4, 5, 6]
list.insert(i, x) → Insert at index
my_list.insert(2, 99)
# Output: [1, 2, 99, 3, 4, 5, 6]
list.remove(x) → Remove first occurrence
my_list.remove(99)
# Output: [1, 2, 3, 4, 5, 6]
list.pop([i]) → Remove and return item at index (default last)
last_item = my_list.pop()
# last_item: 6, my_list: [1, 2, 3, 4, 5]
list.clear() → Remove all elements
my_list.clear()
# Output: []
list.index(x[, start[, end]]) → Find index of first occurrence
index = [10, 20, 30, 40].index(30)
# Output: 2
list.count(x) → Count occurrences of a value
count = [1, 2, 2, 3, 3, 3].count(3)
# Output: 3
list.sort(key=None, reverse=False) → Sort in place