>> Module 02 / Day 18 / Lecture

List Operations

Collections that grow and change
You met lists back in Module 1. Now you'll really work them — add, remove, search, and sort — the everyday verbs of real programs.
Lecture
75 min · 09:00–10:15
Lab
60 min · Roll-call Manager
Module
M2 · Python in Practice
DAY 18 / 40
>> Today's roadmap

The verbs of a list

  1. Lists can change — unlike strings (this is big)
  2. Growing — .append(), .insert()
  3. Shrinking — .remove(), .pop()
  4. Searching — in, .index(), .count()
  5. Ordering — .sort() vs sorted(), len()
  6. Lab — a roll-call manager
>> 01 / 05 · The key difference

Lists are mutable — they change in place

This is the opposite of strings. With a string you had to catch a new value. With a list, the methods change the same list directly.

strings_vs_lists.py
# String — must reassign:
name = name.upper()

# List — changes itself, NO reassign:
marks = [70, 85]
marks.append(90)     # marks is now [70, 85, 90]
# NOT: marks = marks.append(90)  ← returns None!
The trap.
marks = marks.append(90) sets marks to None and loses your list. Just call marks.append(90) on its own line.
>> 02 / 05 · Growing a list

Add items: .append() & .insert()

growing.py
queue = ["Aisha", "Rohit"]

queue.append("Sneha")        # ['Aisha', 'Rohit', 'Sneha'] — adds at END
queue.insert(0, "Vikram")    # ['Vikram', 'Aisha', 'Rohit', 'Sneha']
                            # insert(position, item) — squeezes in
>> 03 / 05 · Shrinking a list

Remove items: .remove() & .pop()

shrinking.py
names = ["Aisha", "Rohit", "Sneha"]

names.remove("Rohit")  # remove by VALUE → ['Aisha','Sneha']

last = names.pop()    # remove by POSITION (default: last)
                      # last == 'Sneha', names == ['Aisha']
first = names.pop(0)  # pop a specific index, returns it
remove vs pop.
.remove("x") = "delete this value". .pop(i) = "delete the item at this position and hand it back to me".
>> 04 / 05 · Searching a list

Is it there? Where? How many?

searching.py
roll = ["Aisha", "Rohit", "Sneha", "Rohit"]

"Sneha" in roll        # True  — the membership test
"Karan" in roll        # False

roll.index("Rohit")      # 1 — position of FIRST match
roll.count("Rohit")      # 2 — how many times it appears
len(roll)               # 4 — how many items total
>> 05 / 05 · Ordering a list

.sort() vs sorted() — know the difference

in_place.py
# .sort() — changes the list itself
marks = [85, 70, 92]
marks.sort()           # marks is now [70, 85, 92]
marks.sort(reverse=True) # [92, 85, 70]
new_copy.py
# sorted() — returns a NEW sorted list
marks = [85, 70, 92]
ranked = sorted(marks)  # [70, 85, 92]
# marks is UNCHANGED: [85, 70, 92]
>> Tying it together

Walk the list, do something to each

Everything from Module 1 still works: loop over a list, and combine these new verbs inside the loop.

together.py
roll = ["aisha", "ROHIT", "sneha"]

# Clean every name (D16) and collect into a new list
clean = []
for name in roll:
    clean.append(name.title())   # build up the result

clean.sort()                     # alphabetical
print(clean, "·", len(clean), "students")
# → ['Aisha', 'Rohit', 'Sneha'] · 3 students
>> Common failures

Four mistakes you'll make today

  1. Writing marks = marks.append(x) — .append returns None, so you lose the list.
  2. .remove("x") when "x" isn't there → ValueError. Check with in first.
  3. Expecting sorted(marks) to change marks — it doesn't; catch the return.
  4. Confusing .remove(value) with .pop(index) — one takes a value, the other a position.
>> 11:00 – 12:00 · Lab

Today's lab — Roll-Call Manager

CORE
A menu over a list

Keep a list of student names. A loop menu lets the user add, remove, search, and list all (sorted, with a count).

★ STRETCH
Guard the edges

Refuse duplicates, handle "remove someone not on the list" gracefully, and ignore stray spaces/case on input.

>> End of Day 18

What you can now do

  • ✓ Grow and shrink lists with .append(), .remove(), .pop().
  • ✓ Search with in, .index(), .count() and order with sort/sorted.
  • ✓ Remember lists are mutable — methods change them in place.
01 / 11
←/→ navigate   F fullscreen   Ctrl/⌘+P save as PDF