List
A list is a mutable, ordered sequence of items. Create a list with square brackets: nums = [1, 2, 3, 4, 5]. Lists can hold items of any type, even mixed ty...
List Basics
A list is a mutable, ordered sequence of items. Create a list with square brackets: nums = [1, 2, 3, 4, 5]. Lists can hold items of any type, even mixed types: mixed = [1, "hello", 3.14, True]. Access items by index (zero-based): nums[0] is 1, nums[-1] is 5. Lists support slicing: nums[1:3] gives [2, 3]. Because lists are mutable, you can change items in place: nums[0] = 99. This mutability distinguishes lists from tuples.
Common List Methods
append(item) adds one item to the end. extend(iterable) adds all items from an iterable. insert(index, item) inserts at a specific position. remove(value) removes the first occurrence of a value (raises ValueError if not found). pop(index) removes and returns the item at index (default is the last). sort() sorts in place. sorted(lst) returns a new sorted list without modifying the original. reverse() reverses in place. index(value) returns the position of the first occurrence. count(value) counts occurrences.
List Operations
Lists support concatenation with +: [1, 2] + [3, 4] gives [1, 2, 3, 4]. Repetition with *: [0] * 5 gives [0, 0, 0, 0, 0]. Membership testing with in: 3 in [1, 2, 3] is True. The len() function returns the number of items. Nested lists (lists of lists) are how Python represents 2D data: matrix = [[1, 2], [3, 4]]; matrix[0][1] accesses element 2. Modifying a nested list also modifies the outer list since both reference the same inner list object.
Copying Lists
Assigning a list to a new name does not copy it: b = a makes b point to the same list. Changes through b also appear through a. To make a shallow copy: b = a.copy() or b = a[:] or b = list(a). A shallow copy creates a new list but does not copy nested objects — they are still shared. For a deep copy (independent nested objects), use: import copy; b = copy.deepcopy(a). This distinction is critical when working with nested mutable data.
Sorting and Searching
list.sort() sorts in place and returns None. sorted(lst) returns a new sorted list and leaves the original unchanged. Both accept a key function and a reverse flag: sorted(words, key=str.lower, reverse=True). To search: index(val) finds the position of the first match. If you need to find all positions, use a list comprehension: [i for i, x in enumerate(lst) if x == val]. For sorted lists, use the bisect module for O(log n) binary search.
Exam Tip
List exam traps: a = [1, 2, 3]; b = a; b.append(4); print(a) gives [1, 2, 3, 4] because a and b refer to the same object. Another classic: list.sort() returns None, not the sorted list. If you write sorted_list = my_list.sort(), sorted_list is None. Use sorted() if you need the return value. Also: remove() removes by value, pop() removes by index. list.clear() empties the list in place; it does not reassign the variable to a new empty list.