Creating A Tuple
Creating A Tuple
In this article, you'll learn everything about Python tuples. More specifically, what are
tuples, how to create them, when to use them and various methods you should be
familiar with.
A tuple in Python 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 parentheses (),
separated by commas. The parentheses are optional, however, it is a good practice
to use them.
A tuple can have any number of items and they may be of different types (integer,
float, list, string, etc.).
script.py
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
my_tuple = (1, 2, 3)
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple
packing.
a, b, c = my_tuple
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")
my_tuple = ("hello",)
# Parentheses is optional
my_tuple = "hello",
print(a) #3
print(b) # 4.6
print(c) # dog
Access Tuple Elements
There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple where the index starts
from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an
element outside of tuple (for example, 6, 7,...) will raise an IndexError.
The index must be an integer; so we cannot use float or other types. This will result
in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the
example below.
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# print(my_tuple[6])
# my_tuple[2.0]
# nested tuple
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
2. Negative Indexing
The index of -1 refers to the last item, -2 to the second last item and so on.
script.py
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
3. Slicing
We can access a range of items in a tuple by using the slicing operator - colon ":".
script.py
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
print(my_tuple[:-7])
print(my_tuple[7:])
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])
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 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).
script.py
my_tuple = (4, 2, 3, [6, 5])
# my_tuple[1] = 9
print(my_tuple)
my_tuple = ('p','r','o','g','r','a','m','i','z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
# Output: (1, 2, 3, 4, 5, 6)
# Repeat
print(("Repeat",) * 3)
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we
cannot delete or remove items from a tuple.
# del my_tuple[3]
del my_tuple
# NameError: name 'my_tuple' is not defined
print(my_tuple)
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the
following two methods are available.
Method Description
count(x
) Returns the number of items x
index(x
) Returns the index of the first item that is equal to x
script.py
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
# In operation
# Output: True
print('a' in my_tuple)
# Output: False
print('b' in my_tuple)
# Not in operation
# Output: True
print('g' not in my_tuple)
# Hello John
# Hello Kate
print("Hello",name)
Since tuples are quite similar to lists, both of them are used in similar situations as
well.
However, there are certain advantages of implementing a tuple over a list. Below
listed are some of the main advantages:
We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
Since tuples 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 a key for a dictionary. With
lists, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.