Back

The pop, append and extend methods in lists - Answers

Q1. Get the code working.

monsters=['goblin', 'orc', 'evil pixie', 'ogre']
extra_evil=['green wizard', 'witch', 'zombie']
bad=['firedog', 'mummy']

print(monsters)
print(extra_evil)
print(bad)

monsters.append('the thing')
print(monsters)

Q2. Append adds the item in brackets to the end of the list.
Q3. Add this code to the end of the program so far:

monsters.pop()
print(monsters)

Q4. pop() removes the last item from the list.
Q5. Change the line above so it reads:

monsters.pop(2)
print(monsters)

Pop(2) removed the item at position 2 (the third item in the list).
Q6. Modify the above line so it reads:

temp = monsters.pop(2)
print(monsters)

print(temp)

Pop() not only removes the item at the position given in the brackets, but returns what was removed as well.
Q7. Append the extra_evil list to the monsters list using this line at the end of the code you have written so far:

monsters.append(extra_evil)
print(monsters)
print('The list monsters has',len(monsters),'elements in it.')

Q8. The list extra_evil is treated as a single element in the monsters list. It is a sublist within the main list and therefore counts as a single element.
Q9. Now extend the bad list to the monsters list using this line at the end of the code you have written so far:

monsters.extend(bad)
print(monsters)
print('The list monsters has',len(monsters),'elements in it.')

Extend adds each of the items in the list called 'bad' to the monsters list. Each item is therefore an element. (Lists can contain a mixture of integers, strings, floats, lists Boolean values etc).
Q10.
Append adds a single item to the end of a list as an element. Extend can add many items to the end of a list, each being a single element in itself.

Back