Python Advanced Collection Methods

Use the key methods of lists, tuples, sets and dictionaries, and know which ones change the collection and which return new values.

Lesson 24 of 107Intermediate12 min read

Python's four built-in collections each come with their own methods. Knowing the important ones, and especially knowing which methods change the collection in place and which return something new, removes a whole category of bugs.

Python
roster = ["Ana", "Ben"]
roster.append("Cara")         # changes roster, returns None
shifts = {"Ana", "Ben"} & {"Ben", "Dev"}   # returns a new set: {'Ben'}

This lesson works through list mutation, the two tuple methods, set algebra and dictionary updates, using a theatre organising its volunteers. It assumes you've met each collection in the lists, dictionaries and tuples and sets lessons.

List mutation

Most list methods modify the list and return None:

MethodEffect
append(x)add one item at the end
extend(iterable)add every item from another iterable
insert(i, x)add an item before position i
remove(x)delete the first item equal to x (ValueError if absent)
pop(i=-1)remove and return the item at i
sort(), reverse(), clear()reorder or empty in place
Python
crew = ["Ana"]
crew.append(["Ben", "Cara"])   # ['Ana', ['Ben', 'Cara']]
crew = ["Ana"]
crew.extend(["Ben", "Cara"])   # ['Ana', 'Ben', 'Cara']

append adds its argument as one item, even if that item is a list; extend adds the items individually. pop() is the exception that returns a value, which makes it useful for treating a list as a stack. Non-mutating alternatives exist for when you need to keep the original: sorted(crew) and reversed(crew) leave crew unchanged.

Tuple queries

Tuples can't change, so they have only two methods, both read-only:

Python
shift_pattern = ("am", "pm", "am", "eve", "am")
print(shift_pattern.count("am"))    # 3
print(shift_pattern.index("eve"))   # 3

index() raises ValueError if the value is missing, and accepts optional start and end positions to search part of the tuple. Lists have the same two methods.

Immutability applies to the tuple's own slots, not to the objects inside it. In pair = ("Ana", ["lights"]) you can't replace pair[1], but pair[1].append("sound") works because the list itself is mutable. If you rely on a tuple being fully constant, for example as a dictionary key, keep only immutable values inside it; Python enforces this for keys by refusing to hash a tuple that contains a list.

Set algebra

Each set operation has an operator form, which needs both sides to be sets, and a method form, which accepts any iterable:

QuestionOperatorMethod
On either shift?a | ba.union(b)
On both shifts?a & ba.intersection(b)
Morning only?a - ba.difference(b)
Exactly one shift?a ^ ba.symmetric_difference(b)
All of a also in b?a <= ba.issubset(b)

These return new sets. Each has an in-place partner that modifies the set instead: |= / update(), &= / intersection_update(), -= / difference_update(). To add or remove single items, use add(), remove() (error if missing) and discard() (no error).

Sets have no order. Printing one may show any order, so when you display results to people, sort them: sorted(a & b).

Dictionary updates

Four dictionary methods handle most reading and writing:

Python
roles = {"tickets": 3}
print(roles.get("stage", 0))        # 0, and "stage" is NOT added
roles.update({"stage": 2, "tickets": 4})
roles.setdefault("lights", 0)       # adds "lights": 0 only if missing
roles.setdefault("tickets", 99)     # tickets stays 4
print(roles)                        # {'tickets': 4, 'stage': 2, 'lights': 0}
  • get(key, default) reads safely without changing the dictionary.
  • update(other) merges another mapping or keyword arguments; existing keys are overwritten.
  • setdefault(key, default) returns the value if the key exists; otherwise it inserts the default and returns it. It's handy for grouping: groups.setdefault(role, []).append(name).
  • pop(key, default) removes a key and returns its value.

keys(), values() and items() return live views: if the dictionary changes, the view reflects it. Changing a dictionary's size while looping over it raises RuntimeError, so loop over list(d.items()) if you need to delete keys as you go.

Independent practice and a worked check

Task: manage a volunteer roster with one operation from each collection family. Add a late volunteer to a list, count a shift in a tuple, find people on both shifts with a set, and update role counts in a dictionary.

Python
roster = ["Ana", "Ben"]
roster.append("Cara")

pattern = ("am", "pm", "am")
am_count = pattern.count("am")

both = {"Ana", "Ben", "Cara"} & {"Ben", "Dev"}

roles = {"tickets": 2}
roles["lights"] = roles.get("lights", 0) + 1

print(roster, am_count, both, roles)
# ['Ana', 'Ben', 'Cara'] 2 {'Ben'} {'tickets': 2, 'lights': 1}

For the worked check, the operation that finds members shared by two sets is the intersection, written a & b or a.intersection(b).

Reference and next practice

The documentation describes list methods, set types and mapping methods. Continue with copying and joining collections and the methods reference. Practise with the Python exercises and Python quiz.

Advanced Collection Methods Summary

  • List mutation: append, extend, sort and reverse change the original list.
  • Tuple queries: Tuples provide count and index without mutating their elements.
  • Set algebra: Union, intersection, difference and symmetric difference answer different membership questions.
  • Dictionary updates: get reads with a default while update merges and setdefault can insert.

Advanced Collection Methods Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Advanced Collection Methods in a small program

Python
morning = {"lights", "sound", "tickets"}
evening = {"sound", "stage"}
print(sorted(morning & evening))
counts = {"tickets": 3}
counts.update({"stage": 2})
print(counts["stage"])
Output
['sound']
2
Line-by-line explanation
  1. Lines 1 to 3& returns the volunteers on both shifts; sorted() turns the set into an ordered list for display.
  2. Lines 4 to 5update() adds the "stage" key while keeping "tickets".
  3. Line 6Reading the newly merged key returns 2.
Example 2

Grouping volunteers by role

Python
signups = [("Ana", "lights"), ("Ben", "tickets"), ("Cara", "lights"),
           ("Dev", "stage"), ("Ana", "tickets")]

by_role = {}
for name, role in signups:
    by_role.setdefault(role, []).append(name)

print(by_role)
print("Most needed:", min(by_role, key=lambda r: len(by_role[r])))

everyone = set()
for names in by_role.values():
    everyone.update(names)
print(sorted(everyone))
print("Ana's roles:", [r for r, names in by_role.items() if "Ana" in names])
Output
{'lights': ['Ana', 'Cara'], 'tickets': ['Ben', 'Ana'], 'stage': ['Dev']}
Most needed: stage
['Ana', 'Ben', 'Cara', 'Dev']
Ana's roles: ['lights', 'tickets']
Line-by-line explanation
  1. Line 6setdefault creates an empty list the first time a role appears, then returns the existing list.
  2. Line 9min with key finds the role with the fewest volunteers.
  3. Line 13update() adds every name from each list; the set removes duplicates.

Common Advanced Collection Methods Mistakes

Expecting get() to add the default

Don't
counts = {}
counts.get("stage", 0)
counts["stage"] += 1        # KeyError: 'stage'
Do
counts = {}
counts["stage"] = counts.get("stage", 0) + 1

get() only reads. Assign the result back, or use setdefault() when you want the default stored.

Saving the result of a mutating method

Don't
crew = ["Ben", "Ana"]
crew = crew.sort()
print(crew)          # None
Do
crew = ["Ben", "Ana"]
crew.sort()          # or: crew = sorted(crew)
print(crew)

Advanced Collection Methods in Real Projects

Collection methods in everyday code

Grouping with setdefault (or collections.defaultdict) turns flat records into categories for reports. Set operations compare lists of IDs: which customers are new this month (this_month - last_month), which users have every required permission (required <= granted). dict.update() and the | operator merge configuration defaults with user settings.

The mutating-versus-returning distinction is so important that Python's design makes it visible: methods that change an object in place return None precisely so you can't accidentally chain them as if they returned a new object.

Advanced Collection Methods FAQ

Which Python list methods return None?

append, extend, insert, remove, sort, reverse and clear all modify the list and return None. pop returns the removed item, while index and count return numbers without changing anything.

What is the difference between setdefault and get?

Both return the existing value when the key is present. When it's missing, get returns the default without changing the dictionary, while setdefault inserts the default and then returns it.

How do I add several items to a set?

Use update() with any iterable: tags.update(["red", "blue"]). Calling add() with a list fails with TypeError: unhashable type: 'list', because add() treats its argument as a single item.

Should I use setdefault or defaultdict?

collections.defaultdict(list) is cleaner when every missing key should start with the same default, because you can write groups[role].append(name) directly. setdefault is handy for one-off cases on an ordinary dictionary.

Why do tuples have so few methods?

Most collection methods exist to change the collection, and tuples are immutable. The only operations left are queries, count() and index(), plus the general tools such as len(), in, slicing and sorted().

Advanced Collection Methods Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which operation finds shared set members?

Multiple choicemedium

Which review concern is valid for advanced collection methods?

Advanced Collection Methods Quiz

2 questions to check what you learned.

  1. Which operation finds shared set members?

    • Union
    • Intersection
    • Python ignores the distinction
  2. Which statement correctly describes set algebra?

    • Union, intersection, difference and symmetric difference answer different membership questions.
    • Only the example output matters, not the rule
    • Every operation has the same behavior