Python Tutorial
Python Lists and List Methods
A list is an ordered, mutable collection that can hold any mix of values and grow or shrink as needed. It is the workhorse data structure in Python: shopping carts, rows from a file, search results, queues of work.
This lesson covers creating lists, indexing and slicing, modifying lists, every list method — append, extend, insert, remove, pop, clear, index, count, sort, reverse, copy — and the difference between shallow and deep copies.
Creating, Indexing and Slicing
Create lists with brackets [1, 2, 3], list(iterable) or comprehensions. Indexes start at 0; negative indexes count from the end (items[-1] is the last item). Slices items[start:stop:step] return new lists; items[::-1] is a reversed copy. Lists can be nested to form tables.
Adding and Removing Items
append(x) adds one item at the end; extend(iterable) adds many; insert(i, x) inserts at a position. remove(x) deletes the first matching value (ValueError if absent); pop(i) removes and returns an item (the last by default); clear() empties the list; del items[i] or del items[a:b] deletes by index or slice.
Searching, Counting and Sorting
index(x) returns the first position of a value; count(x) counts occurrences; x in items tests membership. sort() sorts in place (with key= and reverse=True) and returns None; the built-in sorted() returns a new list. reverse() reverses in place.
Copying Lists
b = a does not copy — both names refer to the same list. a.copy(), a[:] and list(a) make a shallow copy: a new outer list whose inner objects are shared. For nested lists, use copy.deepcopy().
Examples
Indexing, slicing and nested lists
nums = [10, 20, 30, 40, 50, 60]
print(nums[0], nums[-1], nums[2:5], nums[:3], nums[::2], nums[::-1])
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2], [row[0] for row in matrix])
print(len(nums), 30 in nums, min(nums), max(nums), sum(nums))
10 60 [30, 40, 50] [10, 20, 30] [10, 30, 50] [60, 50, 40, 30, 20, 10]
6 [1, 4]
6 True 10 60 210
Every list method
cart = ["pen", "book"]
cart.append("bag"); print("append :", cart)
cart.extend(["ink", "pen"]); print("extend :", cart)
cart.insert(1, "ruler"); print("insert :", cart)
cart.remove("pen"); print("remove :", cart)
last = cart.pop(); print("pop :", last, cart)
first = cart.pop(0); print("pop(0) :", first, cart)
print("index :", cart.index("bag"), "count:", cart.count("ink"))
cart.sort(); print("sort :", cart)
cart.sort(key=len, reverse=True); print("sort key:", cart)
cart.reverse(); print("reverse:", cart)
backup = cart.copy()
cart.clear(); print("clear :", cart, "backup:", backup)
append : ['pen', 'book', 'bag']
extend : ['pen', 'book', 'bag', 'ink', 'pen']
insert : ['pen', 'ruler', 'book', 'bag', 'ink', 'pen']
remove : ['ruler', 'book', 'bag', 'ink', 'pen']
pop : pen ['ruler', 'book', 'bag', 'ink']
pop(0) : ruler ['book', 'bag', 'ink']
index : 1 count: 1
sort : ['bag', 'book', 'ink']
sort key: ['book', 'bag', 'ink']
reverse: ['ink', 'bag', 'book']
clear : [] backup: ['ink', 'bag', 'book']
sort() vs sorted(), sorting records, and slice assignment
students = [("Asha", 91), ("Ravi", 72), ("Meera", 91), ("Kiran", 85)]
ranked = sorted(students, key=lambda s: (-s[1], s[0]))
print(ranked)
print(students[0]) # original unchanged
nums = [5, 3, 8]
print(nums.sort()) # sort() returns None!
print(nums)
letters = list("abcdef")
letters[1:3] = ["X", "Y", "Z"]
del letters[-2:]
print(letters)
[('Asha', 91), ('Meera', 91), ('Kiran', 85), ('Ravi', 72)]
('Asha', 91)
None
[3, 5, 8]
['a', 'X', 'Y', 'Z', 'd']
Aliasing, shallow copy and deep copy
import copy
a = [[1, 2], [3, 4]]
alias = a
shallow = a.copy()
deep = copy.deepcopy(a)
a[0].append(99)
a.append([5])
print("alias :", alias)
print("shallow:", shallow)
print("deep :", deep)
alias : [[1, 2, 99], [3, 4], [5]]
shallow: [[1, 2, 99], [3, 4]]
deep : [[1, 2], [3, 4]]
Common Mistakes
- Writing items = items.sort(), which sets items to None.
- Using append(list) when you meant extend(list), creating a nested list.
- Assuming b = a copies the list.
- Creating a grid with [[0] * 3] * 3, which repeats the same inner list three times.
- Removing items while looping over the same list, which skips elements.
Key Points to Remember
- Lists are ordered, mutable and allow duplicates and mixed types.
- Indexing and slicing (including negative indexes and steps) read and copy parts.
- append/extend/insert add; remove/pop/clear/del delete; index/count search.
- sort() sorts in place and returns None; sorted() returns a new list.
- copy() is shallow; use copy.deepcopy for nested structures.
Practice the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.