Strings & Data Structures
Lists
Complete lesson for Lists using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Lists
Section: Strings & Data Structures. Python lists: ordered, mutable sequences — create, index, slice, methods, copying, and list algorithms.
What is a list?
- A list is an ordered, mutable sequence of objects (any types, mixed allowed).
- Create with
[...]orlist(iterable). Empty list is[]. - Lists keep insertion order and allow duplicates.
- Real life: shopping cart items, playlist tracks, todo tasks.
nums = [10, 20, 30]
print(nums, len(nums), type(nums).__name__)
# Output:
# [10, 20, 30] 3 list Indexing, slicing, and assignment
- Same indexing/slicing rules as strings:
a[0],a[-1],a[1:3],a[::-1]. - Unlike strings, lists support item assignment:
a[0] = 99. - Slice assignment can replace, grow, or shrink:
a[1:3] = [7, 8, 9]. - Deleting:
del a[i],del a[i:j], ora.pop(i).
a = [1, 2, 3, 4]
a[1:3] = [20, 30]
print(a)
# Output:
# [1, 20, 30, 4] Built-in functions that work on lists
- These are **built-in functions** (not list methods). Call them as
len(a), nota.len(). sorted(a)returns a **new** list;list.sort()mutates in place. Prefersortedwhen you must keep the original.
| Function | What it does | Example | Result |
|---|---|---|---|
len(a) | Number of elements | len([10, 20, 30]) | 3 |
list(iterable) | Build a list from an iterable | list("hi") | ["h", "i"] |
sorted(a) | New sorted list (original unchanged) | sorted([3, 1, 2]) | [1, 2, 3] |
reversed(a) | Reverse iterator (not a list) | list(reversed([1, 2])) | [2, 1] |
min(a) / max(a) | Smallest / largest element | min([3, 1, 2]) | 1 |
sum(a) | Sum of numbers | sum([1, 2, 3]) | 6 |
any(a) | True if any element is truthy | any([0, "", 5]) | True |
all(a) | True if all elements are truthy | all([1, 2, 3]) | True |
enumerate(a) | Index + value pairs | list(enumerate(["a","b"])) | [(0, "a"), (1, "b")] |
zip(a, b) | Pair items from iterables | list(zip([1,2], ["x","y"])) | [(1, "x"), (2, "y")] |
map(fn, a) | Apply fn to each item (lazy) | list(map(str, [1, 2])) | ["1", "2"] |
filter(fn, a) | Keep items where fn is true (lazy) | list(filter(bool, [0, 1, ""])) | [1] |
isinstance(a, list) | Type check | isinstance([1], list) | True |
list methods — add and remove
- Call as
a.method(...). Most mutate the list **in place** and returnNone(exceptpop, which returns the removed value). appendadds one object;extendadds each item from an iterable — a classic interview trap.
| Method | What it does | Example | Result / notes |
|---|---|---|---|
a.append(x) | Add one element at the end | [1, 2].append(3) | [1, 2, 3] |
a.extend(iterable) | Add each item from iterable | [1, 2].extend([3, 4]) | [1, 2, 3, 4] |
a.insert(i, x) | Insert x before index i | [1, 3].insert(1, 2) | [1, 2, 3] |
a.remove(x) | Remove first matching value | [1, 2, 1].remove(1) | [2, 1] (error if missing) |
a.pop() | Remove and return last item | [1, 2, 3].pop() | returns 3; list [1, 2] |
a.pop(i) | Remove and return item at i | [1, 2, 3].pop(0) | returns 1; list [2, 3] |
a.clear() | Remove all items | [1, 2].clear() | [] |
del a[i] / del a[i:j] | Delete by index / slice (statement) | del a[0] | Mutates list |
a = [1, 2]
a.append(3)
a.extend([4, 5])
print(a)
# Output:
# [1, 2, 3, 4, 5] append vs extend vs +
append([9])puts the whole list as one element.extend([9])adds9as an element.a + bcreates a new list;a.extend(b)mutatesa.a += bfor lists is likeextend(in-place) whenais a list.- Confusing
appendandextendis a top interview trap.
| Call | Effect on [1, 2] | Returns |
|---|---|---|
append(3) | [1, 2, 3] | None (in place) |
append([3, 4]) | [1, 2, [3, 4]] | None (nested list) |
extend([3, 4]) | [1, 2, 3, 4] | None (in place) |
+ [3, 4] | original unchanged | new list [1, 2, 3, 4] |
+= [3, 4] | [1, 2, 3, 4] | same list object (like extend) |
list methods — search, count, and copy
x in atests membership (linear scan). For many lookups on large data, prefer aset.indexraises if missing; there is no listfindthat returns-1like strings.
| Method / op | What it does | Example | Result |
|---|---|---|---|
x in a | Membership test | 3 in [1, 2, 3] | True |
a.index(x) | First index of x | [3, 1, 3].index(3) | 0 (error if missing) |
a.index(x, start, stop) | Search in a slice range | [1, 2, 3, 2].index(2, 2) | 3 |
a.count(x) | How many times x appears | [3, 1, 3].count(3) | 2 |
a.copy() | Shallow copy | b = a.copy() | new list, same nested objects |
list(a) / a[:] | Other shallow-copy forms | b = a[:] | same idea as copy() |
a = [3, 1, 3, 2]
print(3 in a, a.index(1), a.count(3))
# Output:
# True 1 2 list methods — sort and reverse
a.sort()sorts in place and returnsNone.sorted(a)(built-in) returns a new sorted list.- Both accept
key=andreverse=True. Elements must be comparable unless you supply akey.
| API | What it does | Example | Notes |
|---|---|---|---|
a.sort() | Sort in place | [3, 1, 2].sort() | Returns None; list becomes [1, 2, 3] |
a.sort(reverse=True) | Descending in place | [3, 1, 2].sort(reverse=True) | [3, 2, 1] |
a.sort(key=fn) | Sort by key function | ["bb","a"].sort(key=len) | ["a", "bb"] |
sorted(a) | New sorted list | sorted([3, 1, 2]) | Original unchanged |
a.reverse() | Reverse in place | [1, 2, 3].reverse() | Returns None; list [3, 2, 1] |
reversed(a) | Reverse iterator | list(reversed([1, 2])) | Built-in; does not mutate |
a[::-1] | New reversed list | [1, 2, 3][::-1] | [3, 2, 1] (copy) |
a = [3, 1, 2]
print(sorted(a))
a.sort(reverse=True)
print(a)
# Output:
# [1, 2, 3]
# [3, 2, 1] list APIs — overview cheat sheet
- Use this map to pick the right tool; the tables above have examples.
- Rule of thumb: methods named like verbs often mutate; built-ins like
sorted/lenusually do not.
| Category | Common APIs | Use when |
|---|---|---|
| Built-ins | len, list, sorted, min, max, sum, enumerate, zip | Measure, convert, aggregate, pair |
| Add | append, extend, insert, +, += | Grow a list |
| Remove | remove, pop, clear, del | Delete by value or index |
| Search | in, index, count | Find or tally values |
| Order | sort, sorted, reverse, reversed, slice [::-1] | Sort or flip sequence |
| Copy | copy, list(a), a[:] | Avoid accidental aliasing |
Copying and aliasing
b = amakes an alias — both names point to the same list object.- Shallow copies:
a.copy(),list(a),a[:]. Nested objects are still shared. - Deep copies (
copy.deepcopy) duplicate nested structures. id(a) == id(b)checks whether two names refer to the same object.
a = [1, 2]
b = a
c = a.copy()
b.append(3)
print(a, c)
# Output:
# [1, 2, 3] [1, 2] Nested lists and iteration
- Lists can contain lists: matrices, grids, adjacency lists.
- Iterate rows then columns with nested
forloops. - List comprehensions build new lists compactly:
[x*x for x in a if x > 0]. - Beware
[[0]*3]*3— it reuses the same inner list row (alias bug).
grid = [[1, 2], [3, 4]]
for row in grid:
print(sum(row))
# Output:
# 3
# 7 Advanced — Lists
Shallow vs deep copy
- Shallow copy duplicates the outer list only. Inner mutable objects remain shared.
- Mutating
copy[0].append(...)on a nested structure can surprise you afterlist.copy(). - Use
copy.deepcopywhen you need full independence of nested mutables. - Immutable elements (ints, strs, tuples of immutables) make shallow copies “feel deep”.
import copy
a = [[1], [2]]
b = copy.deepcopy(a)
b[0].append(9)
print(a, b)
# Output:
# [[1], [2]] [[1, 9], [2]] List as stack and queue
- Stack (LIFO):
append/pop()at the end — amortized O(1). - Queue (FIFO):
pop(0)is O(n). Prefercollections.dequefor queues. - Interviews often accept list-as-stack; mention
dequefor queues. dequealso gives O(1)appendleft/popleft.
Complexity cheat sheet
- Index/assign by index: O(1).
append/popend: amortized O(1). insert(0, x),pop(0),remove: O(n) due to shifting.- Membership
inandindex: O(n). sort: O(n log n). Prefer Timsort awareness: partly sorted data is fast.
Comprehensions and filtering
[expr for x in xs if cond]replaces many map/filter loops.- Nested comprehensions can flatten:
[x for row in m for x in row]. - Keep them readable — long comprehensions belong as normal loops.
- Walrus
:=can capture values in filters (3.8+), but do not overuse.
Tricky Interview Points
Q1) How do lists differ from tuples?
Answer Lists are mutable ([]); tuples are immutable (()). Tuples are hashable if elements are hashable; lists never are.
Q2) What is the difference between append and extend?
Answer append adds one object (even if that object is a list). extend adds each element from an iterable.
Q3) sort vs sorted?
Answer list.sort() sorts in place and returns None. sorted(iterable) returns a new list and works on any iterable.
Q4) How do you copy a list?
Answer Shallow: a.copy(), list(a), or a[:]. Deep nested: copy.deepcopy(a). Assignment b = a does not copy.
Q5) Why is [[0]*3]*3 dangerous?
Answer It creates three references to the same inner list. Changing one row changes all rows.
Q6) How do you remove duplicates while preserving order?
Answer Classic approach: list(dict.fromkeys(a)) (3.7+ dicts keep order) or a loop with a seen set.
Q7) Is list membership O(1)?
Answer No. x in list is O(n). Use a set for repeated membership tests.
Q8) What does pop() return?
Answer The removed element. Default index is -1 (last item). Empty list → IndexError.
Q9) Can a list hold mixed types?
Answer Yes. Python lists are heterogeneous by design, though homogeneous lists are clearer in practice.
Q10) How do negative indexes work?
Answer -1 is the last element, -2 second last, and so on. Same idea as strings.
Q11) Difference between remove and pop?
Answer remove(value) deletes by value (first match). pop(index) deletes by position and returns the value.
Q12) What is list aliasing?
Answer Two names referencing the same list object. Mutations through one name are visible through the other.
Simple Programs
Sum and average
nums = [10, 20, 30, 40]
total = sum(nums)
avg = total / len(nums)
print(total, avg)
# Output:
# 100 25.0 Find min and max without min/max
nums = [4, 1, 7, 3]
lo = hi = nums[0]
for n in nums[1:]:
if n < lo:
lo = n
if n > hi:
hi = n
print(lo, hi)
# Output:
# 1 7 Remove duplicates (order kept)
a = [2, 1, 2, 3, 1]
print(list(dict.fromkeys(a)))
# Output:
# [2, 1, 3] Second largest
a = [5, 1, 5, 3, 4]
uniq = sorted(set(a))
print(uniq[-2])
# Output:
# 4 Matrix row sums
m = [[1, 2, 3], [4, 5, 6]]
for row in m:
print(sum(row))
# Output:
# 6
# 15 List as stack
stack = []
stack.append("a")
stack.append("b")
print(stack.pop())
print(stack)
# Output:
# b
# ['a'] Problem Solving Tricks
- Use
appendfor one item,extendfor many — never confuse them. sortreturnsNone; chainsorted(a)when you need an expression.- Copy with
a.copy(); remember shallow vs deep for nested lists. - Build matrices with
[ [0]*cols for _ in range(rows) ], not[[0]*cols]*rows. - Prefer
dequefor queue operations; listpop(0)is O(n). list(dict.fromkeys(a))dedupes and keeps order.- Slice assignment can replace a whole segment in one go.
- Membership-heavy workloads → convert to a
setfirst. - Unpack with
first, *mid, last = awhen lengths vary (3.0+). - Truthiness: empty list is falsy —
if not a:checks empty.
Practice Programs List
- Compute sum, min, max, and average of a list.
- Reverse a list in place and via slicing; compare
ids. - Demonstrate
appendvsextendwith the same argument[9]. - Remove all occurrences of a value without using
removein a loop unsafely. - Sort strings by length using
key=len. - Flatten a 2D list with a nested comprehension.
- Find the second largest distinct value.
- Rotate a list left by k positions using slicing.
- Merge two sorted lists into one sorted list.
- Count frequency of each element and print sorted keys.
- Implement stack push/pop with a list and print states.
- Deep-copy a nested list and prove inner lists are independent.