Drop links or images here to add them to the editor.

In an investigate task you take working code apart to see how each piece contributes to the result. Answer every question for yourself first. You can edit the code and run it to check. Only then open the answer.

The program below is a little menu. It prints four options, reads the number you choose, and does one thing with the list of names depending on which option you picked. It handles one choice and then stops, so run it several times to see every branch.

names = ["Alex", "Anita", "Patrick", "Atif", "Sue"]

print("Enter a number for your choice.")
print("1. Show all")
print("2. Add name")
print("3. Show name")
print("4. Exit")
choice = int(input())

if choice == 1:
    print(names)
elif choice == 2:
    print("Enter the name")
    name = input()
    names.append(name)
elif choice == 3:
    print("Enter the index of the name")
    index = int(input())
    while index < 0 or index >= len(names):
        print("Invalid index - try again")
        index = int(input())
    print(names[index])
else:
    print("Goodbye")

What is the identifier for the list in this program?

Answer

names.

The identifier is the name the programmer chose for the list, and it is the name every line has to use to get at the data. It appears five times here: once on the line that creates the list, and then in print(names), names.append(name), len(names) and names[index].

Watch out for name on the option 2 branch. It is one letter away from names and it is a different thing entirely: an ordinary variable holding the single piece of text the user just typed, which is then appended to the list.

What would happen if you chose option 3 and entered index 0?

Answer

It prints Alex.

The while line checks the index twice before the list is ever touched: it loops while index < 0 or index >= len(names). With index set to 0, 0 < 0 is false and 0 >= 5 is false, so neither half is true, the loop body never runs, and Python goes straight on to print(names[index]).

0 is a perfectly good index. It is the first item in the list, not the one before the list and not the second item. That is what “indexing starts at zero” means in practice.

What would happen if you chose option 3 and entered index 7?

Answer

It does not crash. It prints Invalid index - try again and asks for another number, over and over, until you type one it accepts.

names holds five items, so len(names) is 5 and the valid indices are 0 to

  1. With index set to 7, 7 >= 5 is true, so the while condition is true and the loop body runs: it prints the message and reads a new index. Then the condition is checked again with the new number. Type 9 and it complains again. Type -1 and it complains again, because the other half of the condition, index < 0, catches that. Only a number from 0 to 4 makes both halves false, which ends the loop, and only then does print(names[index]) run.

That loop is the whole point of the program’s design. Without it, print(names[7]) would stop the program with:

IndexError: list index out of range

The loop checks the number before the list is asked for anything, so the error can never happen. Notice that it is written with len(names) rather than with 5: that way it keeps working if the list ever changes length.

What would happen if you chose option 2 and entered the name Stuart?

Answer

Stuart is added to the end of the list, but the program still shows no confirmation that it happened.

The print asks the question, Enter the name, and name = input() stores what you typed; names.append(name) then puts it on the end, so the list becomes ['Alex', 'Anita', 'Patrick', 'Atif', 'Sue', 'Stuart'] and Stuart gets index 5. Nothing on that branch prints the list itself, so the question is the only output after the menu, and nothing shows the append actually happened.

Run the program again and the list is back to its original five names. The program builds the list from scratch on its first line every time it starts, so nothing a previous run added survives.

If you want to see the result, add print(names) after the append, or take option 1 to show the whole list and compare.

What is the purpose of int(input()) on the line that reads the menu choice?

Answer

input() always hands back text, whatever the user typed. int() converts that text into a whole number, so choice holds the number 1 rather than the one-character string "1".

That matters because of what happens next. The conditions compare choice with 1, 2 and 3, and text is never equal to a number: "1" == 1 is False. Take the int() away and all three conditions are false whatever you type, so every run falls through to the else and prints Goodbye.

The same reasoning applies to the two int(input()) calls further down that read the index, with one extra reason: an index has to be a whole number anyway. Handing a list a piece of text between the square brackets stops the program with:

TypeError: list indices must be integers or slices, not str

List operations

Operation What it does How to code it
Output item Outputs a single item from the list. print(list_name[item_index])
print(sweets[3])
Edit item Changes or replaces an item in the list. list_name[item_index] = new data
sweets[1] = "Haribo"
Add an item Puts a new item onto the end of the list. list_name.append(new data)
sweets.append("Galaxy")
Remove an item Removes an item from the list, either by its index or by the data itself. list_name.pop(item_index)
sweets.pop(2)
list_name.pop()
list_name.remove(item)
sweets.remove("Haribo")
Output all items Outputs every item in the list, one by one, using a loop. for i in range(0, len(list_name)):
    print(list_name[i])

for i in range(0, len(sweets)):
    print(sweets[i])

Python also has a built in shortcut that prints the whole list in one line:
print(sweets)
Help! My code doesn't work!

Make sure that you check for the following things:

  • The list name is spelled identically everywhere it is used, capital letters included.
  • The index is surrounded by square brackets.
  • List indexing starts at zero. Are you counting properly?
  • The largest index in a list is one less than the number of items in it.
  • Every line inside a branch or a loop is indented, and all of them by the same amount. Never mix tabs and spaces in one file.