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.
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:
print produces, given that it is handed the whole list
and not one item of it;sentence[1] is, remembering where the counting starts;append and the assignment on the two middle lines each do to the list,
and which one makes it longer;print does not produce the same output as the first one.Need more help with lists? Click here.
| 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 datasweets[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) |
Make sure that you check for the following things: