🌍 Python Programming · subject
Python Programming Data Structures and Collections Syllabus
The Data Structures and Collections syllabus for Python Programming in full: 5 chapters and 21 topics, every one listed below, plus 50 Data Structures and Collections flashcards with answers.
Data Structures and Collections syllabus: all 5 chapters
Expand any chapter to see its topics and sub-topics.
-
Lists
5 topics- Creating and Indexing Lists
- Slicing
- List Methods and Mutation
- List Comprehensions
- Nested and Multidimensional Lists
-
Tuples and Sequences
4 topics- Creating Tuples
- Tuple Packing and Unpacking
- Immutability and Use Cases
- Named Tuples
-
Dictionaries
5 topics- Key-Value Pairs and Creation
- Accessing and Modifying Items
- Dictionary Methods
- Dictionary Comprehensions
- Iterating Over Dictionaries
-
Sets and Frozensets
3 topics- Creating Sets
- Set Operations
- Frozensets
-
Strings as Sequences
4 topics- String Indexing and Slicing
- String Methods
- Character Encoding and Unicode
- Searching and Replacing
Python Programming Data Structures and Collections flashcards — 50 questions with answers
How do you create a list in Python, and what characterizes a list?
A list is created with square brackets, e.g. `nums = [1, 2, 3]` (or via `list()`). It is an ordered, mutable, heterogeneous collection that allows duplicate elements.
What is the index of the first and last element of a list `L = ['a','b','c','d']` using positive and negative indexing?
First element: `L[0]` = 'a'; last element: `L[3]` or `L[-1]` = 'd'. Positive indices start at 0 from the left; negative indices start at -1 from the right.
What happens when you access a list index that is out of range, e.g. `L[10]` on a 3-element list?
Python raises an `IndexError: list index out of range`. Unlike slicing, direct indexing does not tolerate out-of-bounds positions.
What is the general syntax of a slice in Python?
`sequence[start:stop:step]`. It returns elements from `start` (inclusive) up to `stop` (exclusive), moving by `step`. All three parts are optional.
For `L = [0,1,2,3,4,5]`, what does `L[1:4]` return, and why does it exclude index 4?
It returns `[1, 2, 3]`. The `stop` index (4) is exclusive, so slicing yields elements from `start` up to but not including `stop`.
How do you reverse a list using slicing?
Use a step of -1 with empty start/stop: `L[::-1]`. This returns a new reversed copy of the list.
What does `L[:]` produce and why is it useful?
It produces a shallow copy of the entire list. It is useful for duplicating a list so mutations to the copy do not affect the original.
What is the difference between `list.append(x)` and `list.extend(iterable)`?
`append(x)` adds `x` as a single element (a nested item if `x` is a list). `extend(iterable)` adds each element of the iterable individually, lengthening the list by the iterable's size.
What does `list.insert(i, x)` do?
It inserts `x` at index `i`, shifting existing elements from index `i` onward one position to the right. Existing elements are not overwritten.
Compare `list.remove(x)`, `list.pop([i])`, and `del list[i]`.
`remove(x)` deletes the first element equal to `x` (raises `ValueError` if absent). `pop(i)` removes and returns the element at index `i` (default last). `del list[i]` deletes by index and returns nothing.
Why is a list called 'mutable', and what does that imply about `id()` after mutation?
Mutable means its contents can change in place. After methods like `append` or item assignment, the list's `id()` (object identity) stays the same because the same object is modified rather than replaced.
What is the syntax and result of a basic list comprehension that squares numbers 0 through 4?
`[x**2 for x in range(5)]` produces `[0, 1, 4, 9, 16]`. General form: `[expression for item in iterable]`.
How do you add a condition (filter) to a list comprehension?
Place an `if` clause after the loop: `[x for x in range(10) if x % 2 == 0]` yields even numbers `[0,2,4,6,8]`. The `if` filters which items are included.
Where does the conditional expression go when you want an if/else inside a list comprehension?
Before the `for`, as a ternary expression: `[x if x > 0 else 0 for x in nums]`. A filtering `if` goes after the `for`; a value-choosing if/else goes before it.
How do you create a nested list (2D matrix) representing 2 rows of 3 zeros?
`[[0, 0, 0], [0, 0, 0]]`, or with a comprehension `[[0]*3 for _ in range(2)]`. Avoid `[[0]*3]*2`, which makes all rows reference the same inner list.
For a matrix `M = [[1,2,3],[4,5,6]]`, how do you access the element in row 1, column 2?
`M[1][2]` = 6. The first index selects the row (inner list), the second selects the column (element within that list).
Why does `grid = [[0]*3]*2` cause a bug when you set `grid[0][0] = 1`?
All outer elements reference the same inner list, so `grid[0][0] = 1` changes every row, giving `[[1,0,0],[1,0,0]]`. Use `[[0]*3 for _ in range(2)]` to get independent rows.
How do you create a tuple, including the special case of a single-element tuple?
Use parentheses/commas: `t = (1, 2, 3)`. A one-element tuple requires a trailing comma: `t = (5,)`. Without the comma, `(5)` is just the integer 5.
Can you create a tuple without parentheses?
Yes. Commas define a tuple: `t = 1, 2, 3` creates `(1, 2, 3)`. This is called tuple packing.
What is tuple packing versus tuple unpacking?
Packing groups values into a tuple: `t = 1, 2, 3`. Unpacking assigns a tuple's elements to variables: `a, b, c = t`, giving `a=1, b=2, c=3`.
Show the other 30 Data Structures and Collections flashcards
How does extended (starred) unpacking work, e.g. `a, *b, c = [1,2,3,4,5]`?
`a=1`, `c=5`, and `b=[2,3,4]`. The starred variable absorbs all remaining middle elements as a list; only one starred target is allowed.
Why are tuples immutable, and what is one advantage of that immutability?
A tuple's elements cannot be reassigned after creation. Immutability allows tuples to be hashable, so they can serve as dictionary keys or set elements (if their contents are also hashable).
Give a common use case where a tuple is preferred over a list.
Representing fixed, heterogeneous records (e.g. coordinates `(x, y)`), returning multiple values from a function, or as dictionary keys — cases where the data should not change and/or must be hashable.
If a tuple contains a mutable object like `t = (1, [2, 3])`, can that object be changed?
Yes — `t[1].append(4)` works, giving `(1, [2, 3, 4])`. The tuple's references are fixed, but a referenced mutable object can still be modified in place. Such a tuple is not hashable.
How do you define a named tuple, and why use one?
Use `collections.namedtuple`: `Point = namedtuple('Point', ['x', 'y'])`, then `p = Point(1, 2)`. It gives tuple immutability plus named field access (`p.x`), improving readability over positional indexing.
How do you access fields of a named tuple `p = Point(1, 2)`?
Either by name (`p.x`, `p.y`) or by index (`p[0]`, `p[1]`). Named tuples support both attribute-style and positional access.
How do you create a dictionary, and what constitutes each entry?
Use braces with key-value pairs: `d = {'a': 1, 'b': 2}` (or `dict(a=1, b=2)`). Each entry maps a unique, hashable key to a value; keys cannot repeat.
What requirement must dictionary keys satisfy?
Keys must be hashable (immutable types like strings, numbers, or tuples of immutables). Lists and other dicts cannot be keys because they are unhashable/mutable.
How do you access a value by key, and what is the difference between `d['x']` and `d.get('x')`?
`d['x']` returns the value but raises `KeyError` if the key is missing. `d.get('x')` returns `None` (or a supplied default `d.get('x', default)`) instead of raising.
How do you add or update a key-value pair in a dictionary?
Assign to the key: `d['c'] = 3`. If the key exists it updates the value; if not, it inserts a new entry.
What does `dict.setdefault(key, default)` do?
It returns the value for `key` if present; otherwise it inserts `key` with `default` and returns `default`. It is handy for initializing entries (e.g. building lists per key).
What do `dict.keys()`, `dict.values()`, and `dict.items()` return?
View objects: `keys()` gives the keys, `values()` gives the values, and `items()` gives `(key, value)` tuples. Views are dynamic and reflect later changes to the dictionary.
What is the difference between `dict.pop(key)` and `dict.popitem()`?
`pop(key)` removes and returns the value for a given key (raises `KeyError` if absent, unless a default is given). `popitem()` removes and returns the last inserted `(key, value)` pair.
How do you merge two dictionaries `a` and `b` in Python 3.9+?
Use the merge operator: `a | b` creates a new merged dict, or `a |= b` updates `a` in place. Alternatively `a.update(b)` mutates `a`. On key conflicts, `b`'s values win.
Write a dictionary comprehension that maps numbers 0–3 to their squares.
`{x: x**2 for x in range(4)}` produces `{0:0, 1:1, 2:4, 3:9}`. General form: `{key_expr: value_expr for item in iterable}`.
How do you invert a dictionary `d` (swap keys and values) with a comprehension?
`{v: k for k, v in d.items()}`. Note that values must be hashable and unique, or entries will collide and be overwritten.
When you iterate directly over a dictionary with `for x in d:`, what does `x` bind to?
`x` binds to each key. To iterate over values use `for v in d.values()`, and for both use `for k, v in d.items()`.
In modern Python (3.7+), what ordering guarantee do dictionaries provide during iteration?
Dictionaries preserve insertion order, so iteration yields keys in the order they were first inserted. This is a language guarantee as of Python 3.7.
How do you create a set, and what happens to duplicate values?
Use braces of values: `s = {1, 2, 3}` (or `set(iterable)`). Duplicates are automatically discarded, so `{1, 2, 2, 3}` becomes `{1, 2, 3}`. Sets are unordered and mutable.
How do you create an empty set, and why can't you use `{}`?
Use `set()`. `{}` creates an empty dictionary, not a set, because dict syntax claimed the empty-braces notation.
What are the operators for union, intersection, difference, and symmetric difference of sets?
Union: `A | B`; intersection: `A & B`; difference: `A - B`; symmetric difference: `A ^ B` (elements in exactly one set). Each also has a method form (`union`, `intersection`, etc.).
For `A = {1,2,3}` and `B = {2,3,4}`, evaluate `A & B`, `A | B`, `A - B`, and `A ^ B`.
`A & B` = {2,3}; `A | B` = {1,2,3,4}; `A - B` = {1}; `A ^ B` = {1,4}.
How do you test whether set `A` is a subset of set `B`?
Use `A <= B` or `A.issubset(B)`, which is True if every element of `A` is in `B`. Use `A < B` for a proper (strict) subset.
What is a frozenset and how does it differ from a set?
A `frozenset` is an immutable version of a set, created with `frozenset(iterable)`. It supports set operations but not mutation methods (no `add`/`remove`), and being hashable it can be a dict key or an element of another set.
Why can a frozenset be an element of a regular set but a regular set cannot?
Set elements must be hashable. A regular `set` is mutable and therefore unhashable, while a `frozenset` is immutable and hashable, so only the frozenset can be nested.
How do you add and remove elements from a mutable set?
Add with `s.add(x)`. Remove with `s.remove(x)` (raises `KeyError` if absent) or `s.discard(x)` (no error if absent); `s.pop()` removes and returns an arbitrary element.
How does string indexing work, and what does `'Python'[0]` return?
Strings are indexed like sequences: `'Python'[0]` = 'P'. Indexing returns a one-character string; negative indices count from the end, e.g. `'Python'[-1]` = 'n'.
What does `'Python'[1:4]` return, and can you modify a character via `s[0] = 'X'`?
`'Python'[1:4]` = 'yth' (indices 1,2,3). You cannot do `s[0] = 'X'` — strings are immutable, so item assignment raises `TypeError`.
How do you reverse a string and how do you take every second character using slicing?
Reverse: `s[::-1]`. Every second character: `s[::2]`. Slicing with a step controls direction and stride.
Compare lists, tuples, sets, and dictionaries by ordering, mutability, and duplicates.
Lists: ordered, mutable, allow duplicates. Tuples: ordered, immutable, allow duplicates. Sets: unordered, mutable, no duplicates. Dictionaries: ordered (3.7+), mutable, unique keys mapping to values.
Python Programming Data Structures and Collections FAQ
What is in the Python Programming Data Structures and Collections syllabus?
Python Programming Data Structures and Collections is split into 5 chapters: Lists, Tuples and Sequences, Dictionaries, Sets and Frozensets and Strings as Sequences. Together they contain 21 topics.
How many chapters are in Python Programming Data Structures and Collections?
5 chapters, containing 21 topics. The largest chapter is Lists, with 5 topics.
Are there flashcards for Python Programming Data Structures and Collections?
Yes — a 50-card Data Structures and Collections deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.