Hi again Dan, question two about lists. You asked:
“I have letters
which is a list of ten letters. Which one of the
following pieces of code could I use to change the first two elements
to ‘a’ and ‘b’?”
Have you tried them to see which will work? Don’t be scared to try it.
Open the Python interactive interpreter. You should see a “>>>” prompt.
If you need help getting to that, please ask, we’ll be happy to help.
Once you see that prompt, do an experiment:
>>> letters = list('abcdefghij')
>>> print(letters)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> letters[0:1] = ['x', 'y']
>>> print(letters)
['x', 'y', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Hmmm, interesting. The slice letters[0:1]
didn’t replace the first
two items, it replaced the first and inserted a second. What’s going on?
The indexes in a slice represent the spaces between items. So let’s
draw up a picture of what our list looked like, and mark in the slice
positions:
0 1 2 3 4 5 6 7 8 9 10
>a>b>c>d>e>f>g>h>i>j>
So the slice letters[0:1]
begins at position 0 and ends at position 1.
There is only one item between those two positions, ‘a’, so the ‘a’ gets
replaced by two items, ‘x’ and ‘y’.
So to replace the ‘a’ and the ‘b’, our slice needs to start at 0 and go
to 2, not 1. Let’s try it:
>>> letters = list('abcdefghij')
>>> letters[0:2] = ['x', 'y']
>>> print(letters)
['x', 'y', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Success!
The replacement items can be in any iterable object, a list, a tuple,
even a string. So letters[0:2] = ('x', 'y')
would also work. So would
letters[0:2] = 'xy'
.
Changing each item individually would also work:
letters[0] = 'x'
letters[1] = 'y'
but will be slower than using a slice.