Python Tuples
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
Python
Copy Code
types = ( 'Motorbike', 'Car', 'Truck' ) print(types)
Output
( 'Motorbike', 'Car', 'Truck' )
Example: Using the tuple constructor
Python
Copy Code
# 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
Python
Copy Code
types = ( 'Motorbike' ) print(types) print(type(types))
Output
Motorbike <class 'str'>
This is not a Tuple. It's a string
To create a Tuple with a single item you need to add
a trailing comma to the item
Python
Copy Code
types = ( 'Motorbike', ) print(types) print(type(types))
Output
('Motorbike',) <class 'tuple'>
Notes
A Tuple can contain any type of object, and can mix and match object types.
Example: Mixing types in a Tuple
Python
Copy Code
# A tuple containing a string, a number and another Tuple mixedBag = ( 'string', 42, (1,2,3) )
Output
( 'string', 42, (1,2,3) )
Notice that the output has the elements in the tuple in the same order as it was defined.