Slicing lists
Slicing lists is the phrase given to picking out a substring of a list. It follows this pattern:
print(monsters[m:n])
where 'm' is an index that points to the position of the first element in the list 'n' is an index that points up to but not including the last element you want. Remember:
-
- we use square brackets to pick out the slice
- Python starts counting positions from 0 not 1
- 'm' must be less than 'n' or an empty list is returned
- negative indices are possible. The last element in a list starts at position -1, the second last element -2 and so on
- if we miss out m e.g. print(monsters[:n]) we assume m is zero
- if we miss out n e.g. print(monsters[m:]) we assume that n goes to the end of the list
- if we miss out the colon, we are picking out a single element in a list.
Use this for the following questions:
monsters=['goblin', 'orc', 'evil pixie', 'ogre', 'firedog', 'mummy', 'witch']
Predict the answers to these questions. When you think you know what the output will be for each question, run each print line and see if you were correct.
Q1. print(monsters[2:6])
Q2. print(monsters[0:4])
Q3. print(monsters[:3])
Q4. print(monsters[5:2])
Q5. print(monsters[3:11])
Q6. print(monsters[4:])
Q7. print(monsters[:])
Q8. print(monsters[-4:-1])
Q9. print(monsters[-8:])
Q10. print(monsters[:-4])
Q11. print(monsters[0])
Q12. print(monsters[3])
Q13. print(monsters[5])
Q14. print(monsters[-1])
Q15. print(monsters[-5])
Q16. print(monsters[-105])
Q17. print(monsters[2:2*3])
Q18. print(monsters[2.5])
Q19. print(monsters['a'])
Q20. print(monsters[2+2:])