Lesson 6
Dealing with Sequences of Objects
Chapter 7: Tuples
Tuples in robot project
As mentioned, a clear use case for tuples is to represent vectors, for example a coordinate.
You might have found it tedious to keep track of two separate variables row
and col
in your robot project.
Let us group these two variables together and simply call them position
(or coords
if you prefer). A position is now a tuple with two elements, i.e. position = (row, col)
.
Now, try to refactor your project so that you use tuples instead of two separate row
and col
variables to represent the position of a robot (as well as the target cells containing the Ribena). If any of your functions has both the input parameters row
and col
, try to take in only a single tuple
called position
.
You may find that your code becomes more readable at a high-level, since you have abstracted row
and col
to simply position
. In exchange, however, your code might feel less readable at a lower level. For example, row
and col
were actually more self-explanatory than position[0]
and position[1]
! There are ways to make this more readable, but we will worry about that in future lessons! For now, the best way to make this more readable is assign row = position[0]
and col = position[1]
when you need to and use the more self-explanatory row
and col
instead. You can also use row, col = position
or (row, col) = position
which automatically unpacks the elements in position
into the row
and col
variables respectively.
Make sure that your code still works correctly after refactoring. Your output should still stay the same.
Remember to commit your changes to your repo when you are done!