NotesPythonData Structures

Lists

Ordered, mutable collections — indexing, slicing, and the methods you'll use daily.

A list is an ordered, mutable, indexed collection — it can hold mixed types, though in practice you'll mostly keep one type per list.

videos = ["Intro", "Variables", "Loops", "Functions"]
print(videos[0])       # 'Intro'
print(videos[-1])      # 'Functions' -- negative index counts from the end
print(videos[1:3])     # ['Variables', 'Loops'] -- slice, stop excluded

Modifying a list

videos.append("Decorators")        # add to the end
videos.insert(1, "Setup")          # insert at a specific index
videos.remove("Loops")             # remove by value (first match)
last = videos.pop()                # remove & return the last item
videos[0] = "Introduction"         # replace by index
print(videos)

Common list operations

numbers = [5, 3, 8, 1, 9]
print(len(numbers))        # 5
print(sorted(numbers))     # [1, 3, 5, 8, 9] -- returns a NEW sorted list
numbers.sort()             # sorts THIS list in place, returns None
numbers.reverse()          # reverses in place
print(sum(numbers), max(numbers), min(numbers))
print(3 in numbers)        # membership check

sorted(numbers) vs numbers.sort() is a classic trip-up: sorted() is a built-in function that returns a new list and leaves the original untouched; .sort() is a list method that mutates the list in place and returns None — so numbers = numbers.sort() silently throws your data away.

Copying a list — the mutable-object trap

original = [1, 2, 3]
alias = original          # NOT a copy — same list, two names
alias.append(4)
print(original)           # [1, 2, 3, 4] — original changed too!

copy = original.copy()    # or original[:] or list(original)
copy.append(5)
print(original)           # unaffected

Nested lists (2D-style data)

grid = [[1, 2, 3], [4, 5, 6]]
print(grid[1][2])   # 6 -- row 1, column 2
Key points to remember
  • Lists are ordered and mutable — you can change, add, or remove elements after creation.
  • sorted(list) returns a new sorted list; list.sort() mutates in place and returns None — don't assign one to the other.
  • alias = original doesn't copy a list — both names point at the same object; use original.copy() (or original[:]) for a real copy.
  • append() adds one item to the end; extend() adds all items from another iterable; insert() places an item at a specific index.
  • pop() removes and returns an item (by index, default last); remove() deletes the first item matching a value.

Building and modifying a playlist

Revision Flashcards

1 / 3

Tap a card to flip it and see the answer.