Skip to content
Study Hall
Lesson 4 of 5Computer Programming
Unit 5 · Lesson 4 of 5

Lists and Strings

Storing many values under one name, reaching them by index, and processing text.

3 min read10 practice questionsAsk AI about this →

Key things to remember

  1. 1List indexes start at 0; the last valid index is len(list) - 1.
  2. 2len() gives the number of items; range(len(x)) gives exactly the valid indexes.
  3. 3append() adds to the end; marks[i] = v replaces an existing item.
  4. 4for item in list: gives values; for i in range(len(list)): gives indexes.
  5. 5Strings are immutable — methods return a new string rather than changing the original.
  6. 6Slices stop before the end index: s[1:4] gives characters 1, 2 and 3.
  7. 7Always .strip() text input before comparing it.

One variable holds one value. Thirty student marks would need thirty variables, thirty input lines and thirty additions — and it would still break the moment a thirty-first student enrolled. A list holds many values under one name, reached by position, so the same three lines handle any number of them.

A list of length 6 has indexes 0 to 5. There is no element 6.12[0]7[1]9[2]23[3]4[4]16[5]?[6]marks[0] → 12 len(marks) → 6marks[5] → 16 marks[-1] → 16 (Python only)marks[6] → IndexError: list index out of range
Fig 1A list of six items has indexes 0 to 5. There is no item 6.
Indexing starts at zero
The first item is at index 0, so the last item of a list of length n is at index n−1. marks[6] on a six-item list raises an IndexError. This feels arbitrary until you realize the index is really an offset from the start of the block — the first item is zero items along.

Working with lists

PythonWhat it does
marks = [78, 92, 65, 88]Create a list of four numbers
marks[0]The first item: 78
marks[-1]The last item: 88 (Python's negative indexing)
len(marks)How many items: 4
marks.append(70)Add 70 to the end
marks[2] = 70Replace the item at index 2
sum(marks), max(marks), min(marks)Total, largest, smallest
marks.sort()Sort the list in place, smallest first
marks[1:3]A slice: items at index 1 and 2, stopping before 3

There are two ways to loop over a list, and both are worth knowing. for mark in marks: visits each value directly and is the clearer choice whenever you only need the values. for i in range(len(marks)): visits each index, which you need when you want to modify items in place or report a position — "the highest mark was the 4th one".

PythonWhat it does
for mark in marks:Visit each VALUE — clearest when you only need the values
total = total + markAccumulate
for i in range(len(marks)):Visit each INDEX — needed to change items or report a position
marks[i] = marks[i] + 5Modify the list in place
Off-by-one at the end of a list
range(len(marks)) is correct and gives exactly the valid indexes. range(len(marks) + 1) runs one pass too many and crashes with an IndexError on the last one. If a loop over a list crashes on its final pass, this is almost always why.

Strings

A string is a sequence of characters, and it behaves much like a list: it has a length, you can index into it, and you can slice it. The crucial difference is that strings are immutable — you cannot change one character in place. name[0] = "J" raises an error. Instead you build a new string from pieces, which is what every string method does: it returns a new string and leaves the original untouched.

PythonResult for s = "TEJ3M"
len(s)5
s[0]"T"
s[1:4]"EJ3" — stops before index 4
s.upper(), s.lower()"TEJ3M", "tej3m" — returns a NEW string
s + "1""TEJ3M1" — concatenation
"J" in sTrue — membership test
s.replace("3", "4")"TEJ4M" — again, a new string
"a,b,c".split(",")["a", "b", "c"] — string to list
s.strip()Removes leading and trailing whitespace
strip() saves you from invisible bugs
Users type trailing spaces constantly, and "yes " == "yes" is False. Call .strip() on any text input before comparing it, and .lower() too if capitalization should not matter: if answer.strip().lower() == "yes":.

The patterns worth memorizing

TaskPattern
Totaltotal = 0, then total = total + item in the loop
Averagesum(items) / len(items) — guard against an empty list
Count matchingcount = 0, then increment inside an if in the loop
Find the largestStart with the first item, then replace it whenever a bigger one appears
SearchLoop with an if, set a flag or break on a match
Build a new listresult = [], then result.append(value) in the loop
Do not start a maximum search at zero
Setting highest = 0 and then comparing works only if every value is positive. With a list of temperatures like [−5, −12, −3] it returns 0, which is not even in the list. Start with the first item instead: highest = values[0], then loop from index 1.

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
Given marks = [78, 92, 65, 88, 71], write code to print the average and how many marks are 80 or above.
Example 2
Write code that finds the largest value in a list called temps that may contain negative numbers, without using max().
Example 3
A program compares a typed answer with if answer == "yes": and keeps rejecting correct answers. Give two causes and the fix.

Where marks get lost

  • Using list[len(list)] — the last valid index is len(list) - 1.
  • Looping with range(len(x) + 1), which crashes with IndexError on the final pass.
  • Starting a maximum search at 0 when the data can be negative.
  • Expecting s.upper() to change s. Strings are immutable — you must assign the result.
  • Forgetting that a slice stops before its end index.
  • Comparing raw user input without .strip() and .lower().
  • Dividing by len(items) without checking for an empty list, which raises ZeroDivisionError.

Flashcards 10

What is the index of the first item in a list?
What does len(marks) return?
How do you add an item to the end of a list?
What does marks[-1] give?
+ 6 more

Practice

1
For data = [5, 10, 15, 20, 25], what is the value of data[2]?
2
For data = [5, 10, 15, 20, 25], what is the largest valid index?
3
What does "TEJ3M"[1:3] evaluate to?
4
Why does highest = 0 fail as a starting point when searching a list of temperatures?
5
Which method adds a value to the end of a list?
6
A student writes name.upper() and finds name is unchanged. Why?
7
What does len("computer") return?
8
Which loop correctly adds 5 to every mark in a list, modifying the list itself?
9
Match each task to its pattern.
Find the total
Count matching items
Find the largest
Build a filtered list
10
A user types " Yes " and the program compares it to "yes". What is the fix?

Spot a mistake on this page? Let us know