Tuples
Some values belong together and never change: the two coordinates of a place on a map, the day, month and year of a date, or the red, green and blue parts of a color. For values like these, Python has tuples. A tuple is like a list, but it's written in parentheses instead of square brackets:
treasure = (4, 7)
print(treasure)
print(treasure[0])
print(len(treasure))(4, 7)
4
2A tuple has elements separated by commas, as a list does, and you read them by index. len(), in and a for loop work on it too. print() shows a tuple in parentheses.
The difference is that a tuple can't be changed once it has been created. You can't replace an element, and you can't add or remove one:
treasure = (4, 7)
treasure[0] = 5Traceback (most recent call last):
File "<exec>", line 2, in <module>
TypeError: 'tuple' object does not support item assignmentYou know this error from text, which can't be changed either. tuple is Python's name for a tuple, as str is its name for text. A tuple has no .append() either: treasure.append(5) ends with AttributeError: 'tuple' object has no attribute 'append'.
Why would you want a list that can't change? Because some data shouldn't. A point on a map has exactly two coordinates, and the first one is always x. A tuple says so in the code, and Python makes sure that no part of the program changes it by mistake. Use a list for a collection that grows and shrinks, like a shopping list, and a tuple for a few values that together make up one thing, each with its meaning given by its position.
And when the thing really changes, for example a robot moves one step to the right? Then you create a new tuple and store it in the variable, as you store a new text after .upper():
robot = (2, 5)
robot = (robot[0] + 1, robot[1])
print(robot)(3, 5)The tuple (2, 5) wasn't changed. The variable robot now holds a new tuple, made from the values of the old one.
Instructions
- 1
Print where the treasure is. Read x and y from the tuple
treasureby index, so that the program printsTreasure at x = 4, y = 7. Keep the linetreasure = (4, 7)as it is: the exercise also tries your program with the treasure somewhere else. - 2
The player goes 3 steps up, so their y grows by 3. Below, store a new tuple in
player: the same x, and y plus 3, both read from the old tuple. (player[1] += 3would end with the sameTypeErrorastreasure[0] = 5.) Then printplayer:(0, 3). Keep the lineplayer = (0, 0)too.