Lists Deep Dive
Lists Deep Dive
Lists are Python's most versatile built-in data structure. They are ordered, mutable, and can hold items of any type — including other lists.
Creating Lists
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [42, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]Essential List Methods
| Method | Purpose |
|---|---|
append(x) | Add x to the end |
extend(iterable) | Add all items from iterable |
insert(i, x) | Insert x before index i |
remove(x) | Remove first occurrence of x |
pop([i]) | Remove & return item at index i (default: last) |
sort() | Sort in place |
reverse() | Reverse in place |
index(x) | Return first index of x |
count(x) | Count occurrences of x |
copy() | Return a shallow copy |
Slicing
Slice syntax is list[start:stop:step]. All parts are optional:
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nums[2:5] # [2, 3, 4]
nums[:3] # [0, 1, 2]
nums[7:] # [7, 8, 9]
nums[::2] # [0, 2, 4, 6, 8] — every other item
nums[::-1] # [9, 8, ..., 0] — reversedSlices never raise an IndexError, making them safe for boundary cases.
List Multiplication & Concatenation
[0] * 5 # [0, 0, 0, 0, 0]
[1, 2] + [3, 4] # [1, 2, 3, 4]Warning:
[[]] * 3creates three references to the same inner list. Use a list comprehension when you need independent sublists:[[] for _ in range(3)].
Sorting with a Key Function
sort() and the built-in sorted() both accept a key parameter — a callable applied to each element before comparison:
words = ["banana", "fig", "apple", "kiwi"]
words.sort(key=len) # sort by string length
# ["fig", "kiwi", "apple", "banana"]
people = [("Alice", 30), ("Bob", 25), ("Carol", 27)]
people.sort(key=lambda p: p[1]) # sort by ageUse reverse=True in either function for descending order.
Checking Membership & Length
3 in [1, 2, 3, 4] # True
len([10, 20, 30]) # 3Lists vs. Other Sequences
- Use a list when you need a mutable ordered collection.
- Use a tuple when the collection should not change.
- Use a deque (from
collections) for efficient front/back appends.
Code Examples
fruits = ["apple", "banana", "cherry"]
# append — add to end
fruits.append("date")
print(fruits)
# insert — add at index
fruits.insert(1, "avocado")
print(fruits)
# remove — delete by value
fruits.remove("banana")
print(fruits)
# pop — delete by index (returns the item)
removed = fruits.pop(0)
print("Removed:", removed)
print(fruits)
# extend — add multiple items
fruits.extend(["elderberry", "fig"])
print(fruits)append() adds a single item, extend() merges another iterable, insert() places an item at a specific index, remove() deletes by value, and pop() removes by index while returning the deleted element.
nums = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Original:", nums)
print("nums[2:6] =", nums[2:6])
print("nums[:4] =", nums[:4])
print("nums[6:] =", nums[6:])
print("nums[::2] =", nums[::2])
print("nums[::-1] =", nums[::-1])
# Multiplication
zeros = [0] * 5
print("zeros:", zeros)
# Safe independent sublists
matrix = [[] for _ in range(3)]
matrix[0].append(1)
print("matrix:", matrix) # other rows unaffectedSlices use start:stop:step notation and always return a new list. The step -1 efficiently reverses a list. List comprehension is preferred over multiplication when you need independent mutable sublists.
# Sort strings by length
words = ["banana", "fig", "apple", "kiwi", "date"]
words.sort(key=len)
print("By length:", words)
# sorted() returns a new list; sort() modifies in place
original = [3, 1, 4, 1, 5, 9, 2, 6]
ascending = sorted(original)
descending = sorted(original, reverse=True)
print("Ascending: ", ascending)
print("Descending:", descending)
print("Original unchanged:", original)
# Sort list of tuples by second element
people = [("Alice", 30), ("Bob", 25), ("Carol", 27)]
people.sort(key=lambda person: person[1])
print("By age:", people)The key parameter accepts any callable. sort() modifies the list in-place and returns None, while sorted() returns a brand-new sorted list without touching the original.
Quick Quiz
1. What is the difference between list.sort() and sorted(list)?
2. What does nums[::2] return for nums = [0, 1, 2, 3, 4]?
3. Which method removes an item by VALUE (not by index)?
4. Why is [[] for _ in range(3)] preferred over [[]] * 3 for a 2-D list?
Was this lesson helpful?