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
Python Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two methods are available.
Python Tuple Method
Method | Description |
count(x) | Return the number of items that is equal to x |
index(x) | Return index of first item that is equal to x |
>>> my_tuple = ('a','p','p','l','e',)
>>> my_tuple.count('p')
2
>>> my_tuple.index('l')
3
Other Tuple Operations
Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword
in
.
>>> my_tuple = ('a','p','p','l','e',)
>>> 'a' in my_tuple
True
>>> 'b' in my_tuple
False
>>> 'g' not in my_tuple
True
Iterating Through a Tuple
Using a
for
loop we can iterate though each item in a tuple.
>>> for name in ('John','Kate'):
... print("Hello",name)
...
Hello John
Hello Kate
Built-in Functions with Tuple
Built-in functions like
all()
,
any()
,
enumerate()
,
len()
,
max()
,
min()
,
sorted()
,
tuple()
etc. are commonly used with tuple to perform different tasks.
Built-in Functions with Tuple
Function | Description |
all() | Return True if all elements of the tuple are true (or if the tuple is empty). |
any() | Return True if any element of the tuple is true. If the tuple is empty, return False. |
enumerate() | Return an enumerate object. It contains the index and value of all the items of tuple as pairs. |
len() | Return the length (the number of items) in the tuple. |
max() | Return the largest item in the tuple. |
min() | Return the smallest item in the tuple |
sorted() | Take elements in the tuple and return a new sorted list (does not sort the tuple itself). |
sum() | Retrun the sum of all elements in the tuple. |
tuple() | Convert an iterable (list, string, set, dictionary) to a tuple. |
Advantage of Tuple over List
Tuples
and list look quite similar except the fact that one is immutable and
the other is mutable. We generally use tuple for heterogeneous
(different) datatypes and list for homogeneous (similar) datatypes.
There are some advantages of implementing a tuple than a list. Here are a
few of them.
- Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
- Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
- If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
No comments:
Post a Comment