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.
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
| Python | What 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] = 70 | Replace 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".
| Python | What it does |
|---|---|
for mark in marks: | Visit each VALUE — clearest when you only need the values |
total = total + mark | Accumulate |
for i in range(len(marks)): | Visit each INDEX — needed to change items or report a position |
marks[i] = marks[i] + 5 | Modify the list in place |
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.
| Python | Result 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 s | True — 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 |
"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
| Task | Pattern |
|---|---|
| Total | total = 0, then total = total + item in the loop |
| Average | sum(items) / len(items) — guard against an empty list |
| Count matching | count = 0, then increment inside an if in the loop |
| Find the largest | Start with the first item, then replace it whenever a bigger one appears |
| Search | Loop with an if, set a flag or break on a match |
| Build a new list | result = [], then result.append(value) in the loop |
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.