Reversing a List¶
We can use the looping ability of computers, plus the indexing ability, to
manipulate lists in interesting and even surprising ways. In the below program,
we use an accumulator, which is something that accumulates values. We
start with the accumulator so_far
set to an empty list – a list with
nothing in it. As the program executes, it appends items from the source
list into the so_far
list.
Note
Notice the [
and ]
around the value in the source
at the current value of index
. This is needed because you can only concatenate two lists together. Try removing the [
and ]
. What error do you get?
-
csp-16-5-1: Why did the code above end up reversing the list?
- Because we started at 0 and went to len(source).
- That is the normal way of accessing each element, one at a time.
- Because we put the new element ahead of the others in so_far.
- If we had done so_far = so_far + [source[index]], so_far would have just duplicated the list, in order.
- Because of the square brackets around source[index].
- We need those in order to add elements into the list. You can only add a list to a list.