A tuple stores multiple items in a single variable.
You can create a tuple by using parentheses (()) (round brackets).
The tuple collection is ordered (The items have a defined order, and that order will not change.), (changing the order of items after a tuple declaration is not possible.).
The tuple collection is unchangeable (after declaration, you cannot modify the tuple items).
numbers_tuple = (
0, 1, 2, 3, 4, 5
)
print(numbers_tuple)
(0, 1, 2, 3, 4, 5)
In the above example, we declared a tuple of items from 0 to 5 using a parentheses (()) and printing that tuple using the print() function.
There is no restriction on adding the same items to the tuple more than once.
numbers_tuple = (
0, 1, 1, 2, 2, 2
)
print(numbers_tuple)
(0, 1, 1, 2, 2, 2)
In the above example, we added integers 1 and 2 multiple times to the tuple.
There is no restriction on adding similar data type items into the tuple, you can add different data types as well.
tuple1 = (0, 1, 2)
tuple2 = ("Red", "Blue", "Green")
tuple3 = (True, False, True)
tuple4 = (1, "Red", True)
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
(0, 1, 2)
('Red', 'Blue', 'Green')
(True, False, True)
(1, 'Red', True)
In the above example, we created four different tuples (tuple1, tuple2, tuple3, and tuple4) and added different data types of data into the tuple.
In the first tuple, we added integer data type items (tuple1 = (0, 1, 2)) in the second tuple, string data type items (tuple2 = ("Red", "Blue", "Green")) in the third tuple, boolean data type items
(tuple3 = (True, False, True)), and in the fourth tuple, we added a combination of different data type items (tuple4 = (1, "Red", True)).
You can also create a tuple using the tuple() constructor.
numbers_tuple = tuple((0, 1, 2, 3, 4, 5))
print(numbers_tuple)
(0, 1, 2, 3, 4, 5)
In the above example, we use a tuple() constructor for creating the tuple.
To determine how many items are in the tuple, use the len() function.
numbers_tuple = (
0, 1, 2, 3, 4, 5
)
print(len(numbers_tuple))
6
In the above example, the number of items count is 6.
When you put one item in the tuple without adding a comma (,) to the end of an item, then that tuple is not considered a tuple.
Remember to include a comma (,) after an item when creating a tuple with only one item.
tuple1 = (1)
print(type(tuple1))
tuple2 = (1,)
print(type(tuple2))
<'class' 'int'>
<'class' 'tuple'>
In the above example, a tuple with one item is treated as an integer variable, while a tuple with a comma is a tuple variable.