Tuples

What is a tuple?

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.

Declaring a Tuple

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
            

Modifying a Tuple

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.


              acceleration = (0,-9.81)
              acceleration[1] = -32.2
            

              TypeError: 'tuple' object does not support item assignment
            

Looping Through Tuples

You can loop through every element in a tuple just like you did with lists.


            acceleration = (0, -9.81)
            for value in acceleration:
              print(value)
          

            0
            -9.81