How unit 2 is examined
This unit covers Python's built-in collections (list, tuple, dictionary, set), the pandas DataFrame, and indexing and slicing; no question was asked recently, so every topic is taught briefly but completely.
Data Structure: List
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A list is an ordered, mutable collection of items written in square brackets, such as [10, 20, 30].</mark>
Key points.
- A list keeps insertion order, allows duplicate values, and can mix data types such as
[1, "a", 2.5]. - Lists are mutable, so an item can be changed in place:
a[0] = 99. append(x)adds at the end,insert(i, x)adds at position i,extend(list2)joins another list, andremove(x)deletes the first match.pop()removes and returns the last item,sort()orders the list in place, andreverse()reverses it.len(a),min(a),max(a),sum(a)andx in awork on lists, and+joins while*repeats them.- A list comprehension builds a list in one line:
[x*x for x in range(4)]gives[0, 1, 4, 9].
a = [3, 1, 2]
a.append(5); a.sort()
print(a) # [1, 2, 3, 5]
Tuples
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A tuple is an ordered, immutable collection of items written in round brackets, such as (1, 2, 3).</mark>
Key points.
- Items cannot be changed, added or removed after creation, so
t[0] = 5raisesTypeError. - A single-item tuple needs a trailing comma:
(5,)is a tuple but(5)is just an integer. - Tuples are faster and use less memory than lists, so they suit fixed data such as coordinates or days of the week.
- Because they are immutable and hashable, tuples can be used as dictionary keys; lists cannot.
- Indexing, slicing,
len(),+,*,count()andindex()work as in lists:(1,2,2).count(2)is 2. - Tuple packing and unpacking allow
x, y = (1, 2), which is also how a function returns several values.
t = (1, 2, 3)
print(t[1:], len((5,))) # (2, 3) 1
Example. A tuple can hold a list, whose contents can still change even though the tuple itself cannot: t = (1, [2, 3]); t[1].append(4) gives (1, [2, 3, 4]), but t[0] = 9 fails. To edit a tuple, convert it with list(t), change the list, and convert back with tuple().
| Point | List | Tuple |
|---|---|---|
| Brackets | [ ] |
( ) |
| Mutable | Yes | No |
| Speed and memory | Slower, more memory | Faster, less memory |
| Use as dictionary key | No | Yes |
| Methods | Many (append, sort, pop) |
Only count, index |
| Typical use | Data that changes | Fixed records |
Dictionary
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A dictionary is a mutable collection of key-value pairs written in curly brackets, such as {'a': 1, 'b': 2}.</mark>
Key points.
- Each value is reached through its unique key, not by position, and a repeated key keeps only the latest value.
- Keys must be immutable (string, number or tuple), while values can be of any type.
d['c'] = 3adds a new pair or updates an existing one, anddel d['a']ord.pop('a')removes a pair.keys(),values()anditems()return the keys, the values and the (key, value) pairs.d.get(key, default)returns the default instead of raisingKeyErrorwhen the key is missing, whiled['missing']raises it.- Looping with
for k, v in d.items():visits every pair, andkey in dtests for a key.
d = {'a': 1}
d['b'] = 2
print(d.get('c', 0), list(d.keys())) # 0 ['a', 'b']
Example. A student record: st = {'name': 'Ravi', 'roll': 12, 'marks': [70, 80]}. Then st['name'] gives 'Ravi', st['city'] = 'Bhopal' adds a pair, st.pop('roll') removes and returns 12, and len(st) counts the pairs. The update() method merges another dictionary, overwriting equal keys, and clear() empties the dictionary.
Pitfall. Writing d['missing'] raises KeyError; use get() or test key in d first.
DataFrame and Sets
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A set is an unordered collection of unique items written in curly brackets, and a pandas DataFrame is a two-dimensional labelled table of rows and columns.</mark>
Key points.
- A set removes duplicates automatically, has no index or order, and holds only immutable items:
set([1,1,2])gives{1, 2}. - An empty set is made with
set(), because{}creates an empty dictionary. - Set operators are union
|, intersection&, difference-and symmetric difference^:{1,2,3} & {2,3,4}gives{2, 3}. add(x)inserts,remove(x)deletes (error if absent),discard(x)deletes quietly, and<=tests a subset.- A DataFrame is created with
pandas.DataFrame(data), usually from a dictionary of columns or a CSV file read withpd.read_csv(). - Each column of a DataFrame can hold a different data type, and rows and columns carry labels (the index and the column names).
df['name']selects a column,df.loc[label]selects by label,df.iloc[position]selects by position, andhead()anddescribe()inspect the data.
s = {1, 2, 3} | {3, 4}
print(s) # {1, 2, 3, 4}
Example. Building a DataFrame and selecting from it:
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B'], 'marks': [70, 80]})
print(df['marks'].mean()) # 75.0
print(df.iloc[0]['name']) # A
The columns are name and marks, the row labels default to 0 and 1, and df.shape gives (2, 2). New columns are added by assignment, such as df['pass'] = df['marks'] > 75.
| Point | Set | DataFrame |
|---|---|---|
| Type | Built-in collection | pandas table (library) |
| Order | Unordered | Rows and columns labelled and ordered |
| Duplicates | Not allowed | Allowed |
| Dimensions | One | Two |
Constructing, indexing, slicing and content manipulation
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Indexing picks one item by position, and slicing seq[start:stop:step] picks a range of items, excluding the stop position.</mark>
Key points.
- Collections are constructed with literals (
[],(),{}) or with the constructorslist(),tuple(),set()anddict(), which also convert one type to another. - Indexes start at 0, and negative indexes count from the end, so
a[-1]is the last item; an index beyond the length raisesIndexError. - In
a[1:3]the start is included and the stop is excluded, so it gives items 1 and 2, and omitted bounds default to the ends. - The step sets the stride, so
a[::2]takes every second item anda[::-1]reverses the sequence. - A slice of a list can be assigned to change its content:
b = [1,2,3,4,5]; b[1:3] = [9]gives[1, 9, 4, 5]. del b[0]removes an item, and after that deletion[1, 9, 4, 5]becomes[9, 4, 5].- Slicing works on lists, tuples and strings, but a tuple or string slice makes a new object because these cannot be edited.
a = [10, 20, 30]; a.append(40)
print(a[1:3], a[-1], a[::-1]) # [20, 30] 40 [40, 30, 20, 10]
Example. Slicing a string and a tuple: "python"[1:4] gives 'yth', and (10,20,30,40)[::2] gives (10, 30). Slicing never raises an error for out-of-range bounds: [1,2,3][1:10] gives [2, 3].
Steps. To manipulate a list's content in the exam, follow this order: create the list, index or slice to read, assign to an index or slice to change, use append or insert to add, use remove, pop or del to delete, and finally sort or reverse to reorder.
| Operation | Syntax | Result for a = [1,2,3,4] |
|---|---|---|
| Read one item | a[2] |
3 |
| Read a range | a[1:3] |
[2, 3] |
| Change an item | a[0] = 7 |
[7, 2, 3, 4] |
| Insert | a.insert(1, 8) |
[1, 8, 2, 3, 4] |
| Delete by value | a.remove(3) |
[1, 2, 4] |
| Delete by index | del a[0] |
[2, 3, 4] |
Last-minute revision
- A list is ordered and mutable and is written in
[]; a tuple is ordered and immutable and is written in(). (5,)is a tuple, but(5)is an integer.- A dictionary holds key-value pairs in
{}; keys are unique and immutable, and values can be anything. d.get(k, default)avoidsKeyError.- A set is unordered and unique;
{}is an empty dictionary andset()is an empty set. - Set operators are
|union,&intersection,-difference and^symmetric difference. - A DataFrame is a 2-D labelled table from pandas;
locselects by label andilocby position. - A slice
seq[start:stop:step]excludesstop, and[::-1]reverses. - The negative index
-1is the last item, and indexes start at 0. - Lists and dictionaries are mutable; tuples, strings and set items are immutable.
appendadds one item andextendadds many;popremoves and returns.
Memory hooks
- Tuple is "tough": once made it cannot be changed.
- List is "loose": items can be freely edited, added and removed.
- A dictionary works like a phone book: the name (key) gives the number (value).
- A set is a bag of unique marbles: no order and no repeats.
- A slice stops before the stop index, like a fence post that is not counted.
- Round brackets for tuple, square for list, curly for dictionary and set.
Coverage checklist
- Data Structure: List: definition, mutability, methods and comprehension (no past questions).
- Tuples: immutability, single-item comma, packing (no past questions).
- Dictionary: key-value pairs, methods,
get(no past questions). - DataFrame and Sets: set operators, DataFrame creation and selection (no past questions).
- constructing, indexing, slicing and content manipulation: constructors, indexes, slices, slice assignment (no past questions).