Naming the columns
Show on a big screenA name is not a place in the rows. A position is. The headers list holds the four column names in order. The code headers.indexOf(name) gives the position of that name in the list.
- The headers list, four names in order.
- Positions are written below: 0 to 3.
indexOf('due')points at position 3.indexOf('marks')finds nothing: answer −1.
The rule
The headers list turns a column's name into a position. Find the position first, then fetch the field. Minus one is an answer. Do not use it as a position. It means no such column exists.
A function is named code that gives back one value. Here wanted is the column name to find.
function fieldIndex(headers, wanted) {return headers.indexOf(wanted);}
indexOf gives −1 when the name is not in the list. Columns sit at positions 0 and up. So −1 is no column's position.
fieldIndex(headers, 'name') gives 1. fieldIndex(headers, 'marks') gives −1, because the register has no marks column.
Suppose the school changes the order of the columns. headers.indexOf still finds the right one. A hand-typed position such as 3 would name the wrong column.
Watch out!
In real Python, a fetch at −1 does not stop. It quietly gives the last field. So check for −1 before you fetch.
The mistake comes only when you fetch with −1. Then this course's runner stops. It names the position and the row's length.
Below, make fieldIndex give the right position. It must also answer for a missing column, such as marks.
Loading lab…
A position-finder answers every question — with a position, or with −1.
Try the lab to finish this lesson.