Key Terms
- Tuple
- An list which cannot be changed after being declared.
A tuple is an immutable list. It's a list that cannot be changed once its defined. Tuples can be used to store data that isn't meant to be altered such as menu options in a game or the constant for acceleration due to gravity affecting all projectiles in your game.
Fortunately, most of the ideas that we learned from lists carry over - just not the methods and functions that added and deleted elements since tuples are immutable.
Declaring a tuple is as the same as a list with the exception that you use parenthesis to enclose the elements rather than square brackets.
acceleration = (0,-9.81)
print(acceleration[0])
print(acceleration[1])
0
-9.81
If we try to modify any of the elements in a tuple, you will get the
error
TypeError: 'tuple' object does not support item assignment.. This is the expected behavior and if you find yourself in needing
to modify a tuple often - you should consider using a list instead.
TypeError: 'tuple' object does not support item assignment
You can loop through every element in a tuple just like you did with lists.
0
-9.81