Drop hier links of afbeeldingen om ze aan de editor toe te voegen.

In a predict and run task you do not write code from scratch. You start from a small piece of working code, work out what you think it will do before you run it, and then run it to check whether you were right.

Predict

Study the code below carefully and write down a prediction of what it will do when it runs. Your prediction should use the key terms list, item and index. You can type it straight into the code as a comment, on a line starting with #.

Seven lines run one after the other, and four of them print something, so your prediction needs four lines of output in the right order. Two of the lines change the list before the last print ever happens, so it is worth working out what the list holds at each stage rather than only at the start.

Only once you have written your prediction should you run the code and compare the result with what you expected. Where the two differ, add a comment saying what actually happened and why.

sentence = ["Always", "look", "on", "the", "bright", "side", "of"]
print(sentence)
print(sentence[1])
sentence.append("life")
sentence[4] = "sunny"
print(sentence[4])
print(sentence[0] + " " + sentence[3])
print(sentence)

Four things are worth deciding before you run it:

Need more help with lists? Click here.

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.