Skip to main content

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.

L1

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 [...] or list(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], or a.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), not a.len().
  • sorted(a) returns a **new** list; list.sort() mutates in place. Prefer sorted when you must keep the original.
FunctionWhat it doesExampleResult
len(a)Number of elementslen([10, 20, 30])3
list(iterable)Build a list from an iterablelist("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 elementmin([3, 1, 2])1
sum(a)Sum of numberssum([1, 2, 3])6
any(a)True if any element is truthyany([0, "", 5])True
all(a)True if all elements are truthyall([1, 2, 3])True
enumerate(a)Index + value pairslist(enumerate(["a","b"]))[(0, "a"), (1, "b")]
zip(a, b)Pair items from iterableslist(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 checkisinstance([1], list)True

list methods — add and remove

  • Call as a.method(...). Most mutate the list **in place** and return None (except pop, which returns the removed value).
  • append adds one object; extend adds each item from an iterable — a classic interview trap.
MethodWhat it doesExampleResult / 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]) adds 9 as an element.
  • a + b creates a new list; a.extend(b) mutates a.
  • a += b for lists is like extend (in-place) when a is a list.
  • Confusing append and extend is a top interview trap.
CallEffect 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 unchangednew list [1, 2, 3, 4]
+= [3, 4][1, 2, 3, 4]same list object (like extend)

list methods — search, count, and copy

  • x in a tests membership (linear scan). For many lookups on large data, prefer a set.
  • index raises if missing; there is no list find that returns -1 like strings.
Method / opWhat it doesExampleResult
x in aMembership test3 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 copyb = a.copy()new list, same nested objects
list(a) / a[:]Other shallow-copy formsb = 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 returns None. sorted(a) (built-in) returns a new sorted list.
  • Both accept key= and reverse=True. Elements must be comparable unless you supply a key.
APIWhat it doesExampleNotes
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 listsorted([3, 1, 2])Original unchanged
a.reverse()Reverse in place[1, 2, 3].reverse()Returns None; list [3, 2, 1]
reversed(a)Reverse iteratorlist(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 / len usually do not.
CategoryCommon APIsUse when
Built-inslen, list, sorted, min, max, sum, enumerate, zipMeasure, convert, aggregate, pair
Addappend, extend, insert, +, +=Grow a list
Removeremove, pop, clear, delDelete by value or index
Searchin, index, countFind or tally values
Ordersort, sorted, reverse, reversed, slice [::-1]Sort or flip sequence
Copycopy, list(a), a[:]Avoid accidental aliasing

Copying and aliasing

  • b = a makes 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 for loops.
  • 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
L2

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 after list.copy().
  • Use copy.deepcopy when 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). Prefer collections.deque for queues.
  • Interviews often accept list-as-stack; mention deque for queues.
  • deque also gives O(1) appendleft / popleft.

Complexity cheat sheet

  • Index/assign by index: O(1). append/pop end: amortized O(1).
  • insert(0, x), pop(0), remove: O(n) due to shifting.
  • Membership in and index: 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.
L3

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.

L4

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']
L5

Problem Solving Tricks

  • Use append for one item, extend for many — never confuse them.
  • sort returns None; chain sorted(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 deque for queue operations; list pop(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 set first.
  • Unpack with first, *mid, last = a when lengths vary (3.0+).
  • Truthiness: empty list is falsy — if not a: checks empty.
L6

Practice Programs List

  1. Compute sum, min, max, and average of a list.
  2. Reverse a list in place and via slicing; compare ids.
  3. Demonstrate append vs extend with the same argument [9].
  4. Remove all occurrences of a value without using remove in a loop unsafely.
  5. Sort strings by length using key=len.
  6. Flatten a 2D list with a nested comprehension.
  7. Find the second largest distinct value.
  8. Rotate a list left by k positions using slicing.
  9. Merge two sorted lists into one sorted list.
  10. Count frequency of each element and print sorted keys.
  11. Implement stack push/pop with a list and print states.
  12. Deep-copy a nested list and prove inner lists are independent.