Proof Academy · Python · Journey 05

Strings, lists and records

Clean text, follow indices and keep a collection of accepted records.

Lab and core lesson: 40–50 minutes, plus guided study · Builds on Loops and running totals

01 · Understand and predict

Choose how to represent each value

A string is an ordered sequence of characters. Index 0 is the first character. A slice such as name[0:2] includes indices 0 and 1. String methods such as strip() and upper() return new strings. Assign the result if you want to keep it.

A list holds a sequence of items. append() adds one item to an existing list. Loop directly over the items when you only need their values. Use an index when you need a position. A record such as ['K07', 8] groups fields about one entry. A list of those records gives you rows and columns.

entries = [" A12 ", "", "b07"]
labels = []
for entry in entries:
    label = entry.strip().upper()
    if label != "":
        labels.append(label)
print(labels[1])

Worked trace

  1. The first entry becomes A12, which is appended at index 0.
  2. The blank entry is skipped, so the list still has one item.
  3. The last entry becomes B07 and is appended at index 1. The output is B07.
If the last entry were also blank, what would happen at print(labels[1])?

From code to machine. A list is a way to organise values in memory while a program runs. The list position is a Python index. The runtime looks up the stored reference for that index, which is a different idea from naming a physical RAM address.

Guided study

Read it, trace it, test it

Read the position before you read the value

An index says where to look. It is not the data at that position. In codes = ["K02", "B15", "M09"], codes[1] is "B15". In the string "B15", index 1 gives "1". Put the two steps together and codes[1][1] gives "1". When you read unfamiliar code, identify whether each pair of brackets selects a record, a field or a character. Draw the list before doing arithmetic on its indices.

Index012
CodeK02B15M09
Character in B15B15

A slice stops before the second number. "B15"[1:3] gives "15". "B15"[:1] gives "B". A slice shorter than you expect can still be legal, while a single index outside the string or list causes IndexError. If a task guarantees three-character codes, state that assumption in your plan. If the data can be incomplete, check the length before indexing a required character.

Trace normalisation and filtering

raw = [" bx2 ", "BX2", "a", "m07"]
kept = []
for item in raw:
    code = item.strip().upper()
    if len(code) == 3 and code not in kept:
        kept.append(code)
print(",".join(kept))

The first item is cleaned to BX2 and kept. The second also becomes BX2, so the membership check rejects the duplicate. The third becomes A and fails the length check. The final item becomes M07 and is appended after BX2. The result is BX2,M07. The list keeps the order in which accepted items were found. Sorting the list would solve a different problem. Notice how join builds one string from the items with the separator between them, so there is no comma after the final code.

strip() and upper() return a result. kept.append(code) modifies the existing list. Do not write kept = kept.append(code). The method changes the list but returns None. Also choose between looping over values and looping over positions. for code in kept is enough if you only need the values. for index in range(len(kept)) lets you use the position as well, for example when reporting where the first match occurred.

Store and inspect records

A list such as [["BX2", 6], ["M07", 9]] contains two rows. records[1][0] is the code "M07" and records[1][1] is its score 9. If you are reading a file, split a line into fields first, check that the row has the expected number of fields, and convert only the numeric field. A code like "007" should stay as text if the zeros identify the record.

Practise a Paper 2 change request

Write a short program for a list of team codes. Read a count, then read each code. Clean it with strip() and upper(). Keep a record of the code and its original one-based input position, accepting only three-character codes. Print the position of the first M07, or -1 when it is absent. Plan tests for a duplicate, a short code before the match, and no match. In the browser editor supply the count and each code on its own line. The lesson’s existing case checker tests a different output contract, so use Run with my input for this practice.

Check whether two names refer to one list

second = first makes both names refer to the same list. If you append through second, the change is visible through first too. Use first.copy() when you need a separate shallow copy of a list of codes.

Check your guided practice

For 5, ab1, x, m07, M07, bx2, the answer is 3. Count input positions even when a code is rejected. The accepted records are AB1 at 1, M07 at 3 and 4, and BX2 at 5 if you keep duplicate records. The search stops at the first match. Using the position in the filtered list would incorrectly report 2.

02 · Run and repair

Clean a label before slicing it

The label maker should trim spaces, convert to uppercase, then display the first two characters. Run it with ' b07 ' and find why the changes are missing.

One line for input(). Leave the box empty to test a blank entry.

Ready to run.

Need a hint?

Assign the result of the chained methods back to label before slicing.

03 · Build independently

Make a list of unique team codes

Read a count on the first line, then that many codes. Build an ordered list of accepted codes.

  • Trim spaces and convert each code to uppercase. Accept only codes of length three.
  • Keep the first occurrence of each cleaned code. Use a list and membership testing to avoid duplicates.
  • Print the accepted codes separated by commas with no spaces. Print an empty line if none are accepted.

Enter one value per line. Each input() reads the next line.

Ready to run.

Need a hint?

Initialise an empty list. If len(code) == 3 and code not in codes, append it. Use ','.join(codes) after the loop.

04 · Explain and transfer

Explain your reasoning

Why should membership be checked after cleaning the code?

Compare your explanation

Before cleaning, ' ab1 ' and 'AB1' are distinct strings. Cleaning first makes both AB1, so membership detects the duplicate.

Independent follow-up. Store each accepted code together with the input position of its first occurrence. For three duplicate spellings, show why the position stays the same.

Original GCSE practice · Pearson Edexcel 1CP2 1.2.2, 6.2.2, 6.3.1, 6.3.3 and 6.4.3. Download your .py file to keep it after leaving the page.

Next: Functions and program structure →