Tuples allow multiple values to be stored as a collection.
- The collection of values in a tuple cannot be changed once it has been initialised. Tuples are immutable.
- The values in a Tuple are ordered, meaning they can be accessed in a consistent order.
- Tuples are indexed, meaning you can access each element via an index which starts at 0.
- Tuples can have repeated items.
Example: Creating a Tuple
types = ( 'Motorbike', 'Car', 'Truck' ) print(types)
( 'Motorbike', 'Car', 'Truck' )
Example: Using the tuple constructor
# Pass in a tuple to the "tuple()" constructor. types = tuple( ('Motorbike', 'Car', 'Truck') )
Example: Creating a Tuple wuth one element
One would assume that creating a Tuple one element was as simple as
types = ( 'Motorbike' ) print(types) print(type(types))
Motorbike <class 'str'>
This is not a Tuple. It's a string
types = ( 'Motorbike', ) print(types) print(type(types))
('Motorbike',) <class 'tuple'>
A Tuple can contain any type of object, and can mix and match object types.
Example: Mixing types in a Tuple
# A tuple containing a string, a number and another Tuple mixedBag = ( 'string', 42, (1,2,3) )
( 'string', 42, (1,2,3) )
Notice that the output has the elements in the tuple in the same order as it was defined.