In Python programming, tuple is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The parentheses are optional but is a good practice to write it. A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).
# empty tuple
my_tuple = ()
# tuple having integers
my_tuple = (1, 2, 3)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# tuple can be created without parentheses
# also called tuple packing
my_tuple = 3, 4.6, "dog"
# tuple unpacking is also possible
a, b, c = my_tuple
Creating a tuple with one element is a bit tricky. Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is in fact a tuple.
>>> my_tuple = ("hello") # only parentheses is not enough
>>> type(my_tuple)
<class 'str'>
>>> my_tuple = ("hello",) # need a comma at the end
>>> type(my_tuple)
<class 'tuple'>
>>> my_tuple = "hello", # parentheses is optional
>>> type(my_tuple)
<class 'tuple'>
Accessing Elements in a Tuple
There are various ways in which we can access the elements of a tuple.
Indexing
We can use the index operator [] to access an item in a tuple. Index starts from 0. So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element other that this will raise an IndexError
. The index must be an integer. We can’t use float or other types, this will result into TypeError
. Nested tuple are accessed using nested indexing.
>>> my_tuple = ['p','e','r','m','i','t']
>>> my_tuple[0]
'p'
>>> my_tuple[5]
't'
>>> my_tuple[6] # index must be in range
...
IndexError: list index out of range
>>> my_tuple[2.0] # index must be an integer
...
TypeError: list indices must be integers, not float
>>> n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
>>> n_tuple[0][3] # nested index
's'
>>> n_tuple[1][1] # nested index
4
>>> n_tuple[2][0] # nested index
1
Negative Indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
>>> my_tuple = ['p','e','r','m','i','t']
>>> my_tuple[-1]
't'
>>> my_tuple[-6]
'p'
Slicing
We can access a range of items in a tuple by using the slicing operator (colon).
>>> my_tuple = ('p','r','o','g','r','a','m','i','z')
>>> my_tuple[1:4] # elements 2nd to 4th
('r', 'o', 'g')
>>> my_tuple[:-7] # elements beginning to 2nd
('p', 'r')
>>> my_tuple[7:] # elements 8th to end
('i', 'z')
>>> my_tuple[:] # elements beginning to end
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need the index that will slice the portion from the tuple.
Changing or Deleting a Tuple
Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once it has been assigned. But if the element is itself a mutable datatype like list, its nested items can be changed. We can also assign a tuple to different values (reassignment).
>>> my_tuple = (4, 2, 3, [6, 5])
>>> my_tuple[1] = 9 # we cannot change an element
...
TypeError: 'tuple' object does not support item assignment
>>> my_tuple[3] = 9 # we cannot change an element
...
TypeError: 'tuple' object does not support item assignment
>>> my_tuple[3][0] = 9 # but item of mutable element can be changed
>>> my_tuple
(4, 2, 3, [9, 5])
>>> my_tuple = ('p','r','o','g','r','a','m','i','z') # tuples can be reassigned
>>> my_tuple
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
We can use + operator to combine two tuples. This is also called concatenation. The * operator repeats a tuple for the given number of times. These operations result into a new tuple.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> ("Repeat",) * 3
('Repeat', 'Repeat', 'Repeat')
We cannot delete or remove items from a tuple. But deleting the tuple entirely is possible using the keyword del
.
>>> my_tuple = ('p','r','o','g','r','a','m','i','z')
>>> del my_tuple[3] # can't delete items
...
TypeError: 'tuple' object doesn't support item deletion
>>> del my_tuple # can delete entire tuple
>>> my_tuple
...
NameError: name 'my_tuple' is not defined