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 we
can change the elements of a list.
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.).
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
In the above example, we have created different
types of tuples and stored different data items inside
them.
As mentioned earlier, we can also create tuples
without using parentheses:
my_tuple = 1, 2, 3
my_tuple = 1, "Hello", 3.4
Create a Python Tuple With one Element
In Python, 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 a
tuple,
var1 = ("Hello") # string
var2 = ("Hello",) # tuple
We can use the type() function to know which class
a variable or a value belongs to.
var1 = ("hello")
print(type(var1)) # <class 'str'>
# Creating a tuple having one element
var2 = ("hello",)
print(type(var2)) # <class 'tuple'>
# Parentheses is optional
var3 = "hello",
print(type(var3)) # <class 'tuple'>
Here,
("hello") is a string so type() returns str as
class of var1 i.e. <class 'str'>
("hello",) and "hello", both are tuples
so type() returns tuple as class
of var1 i.e. <class 'tuple'>
Access Python Tuple Elements
Like a list, each element of a tuple is represented by
index numbers (0, 1, ...) where the first element is at
index 0.
We use the index number to access tuple elements.
For example,
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 index outside of the tuple
index range(6,7,... in this example) 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.
# accessing tuple elements using indexing
letters = ("p", "r", "o", "g", "r", "a", "m",
"i", "z")
print(letters[0]) # prints "p"
print(letters[5]) # prints "a"
In the above example,
letters[0] - accesses the first element
letters[5] - accesses the sixth element
2. 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. For example,
# accessing tuple elements using negative
indexing
letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm',
'i', 'z')
print(letters[-1]) # prints 'z'
print(letters[-3]) # prints 'm'
In the above example,
letters[-1] - accesses last element
letters[-3] - accesses third last element
3. Slicing
We can access a range of items in a tuple by using
the slicing operator colon :.
# accessing tuple elements using slicing
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm',
'i', 'z')
# elements 2nd to 4th index
print(my_tuple[1:4]) # prints ('r', 'o',
'g')
# elements beginning to 2nd
print(my_tuple[:-7]) # prints ('p', 'r')
# elements 8th to end
print(my_tuple[7:]) # prints ('i', 'z')
# elements beginning to end
print(my_tuple[:]) # Prints ('p', 'r', 'o',
'g', 'r', 'a', 'm', 'i', 'z')
Output
('r', 'o', 'g')
('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Here,
my_tuple[1:4] returns a tuple with elements
from index 1 to index 3.
my_tuple[:-7] returns a tuple with elements
from beginning to index 2.
my_tuple[7:] returns a tuple with elements from
index 7 to the end.
my_tuple[:] returns all tuple items.
Note: When we slice lists, the start index is inclusive
but the end index is exclusive.
Python Tuple Methods
In Python ,methods that add items or remove items
are not available with tuple. Only the following two
methods are available.
Some examples of Python tuple methods:
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # prints 2
print(my_tuple.index('l')) # prints 3
Here,
my_tuple.count('p') - counts total number
of 'p' in my_tuple
my_tuple.index('l') - returns the first
occurrence of 'l' in my_tuple
Iterating through a Tuple in Python
We can use the for loop to iterate over the elements
of a tuple. For example,
languages = ('Python', 'Swift', 'C++')
# iterating through the tuple
for language in languages:
print(language)
Output
Python
Swift
C++
Check if an Item Exists in the Python Tuple
We use the in keyword to check if an item exists in
the tuple or not. For example,
languages = ('Python', 'Swift', 'C++')
print('C' in languages) # False
print('Python' in languages) # True
Here,
'C' is not present in languages, 'C' in
languages evaluates to False.
'Python' is present in languages, 'Python' in
languages evaluates to True.
Advantages of Tuple over List in Python
Since tuples are quite similar to lists, both of them
are used in similar situations.
However, there are certain advantages of
implementing a tuple over a list:
We generally use tuples for heterogeneous
(different) data types and lists for homogeneous
(similar) data types.
Since tuples are immutable, iterating through a
tuple is faster than with a 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.
In Python, tuples are immutable i.e. once created
we can not change its contents. But sometimes we
want to modify the existing tuple, in that case we
need to create a new tuple with updated elements
only from the existing tuple.
Let’s see how to insert, modify and delete the
elements from tuple.
Append an element in Tuple at end
Suppose we have a tuple i.e.
# Create a tuple
tupleObj = (12 , 34, 45, 22, 33 )
Now to append an element in this tuple, we need to
create a copy of existing tuple and then add new
element to it using + operator i.e.
# Append 19 at the end of tuple
tupleObj = tupleObj + (19 ,)
We will assign the new tuple back to original
reference, hence it will give an effect that new
element is added to existing tuple.
Contents of tuple will be now,
(12, 34, 45, 22, 33, 19)
A new Element is appended at the end of tuple.
Insert an element at specific position in tuple
To insert an element at a specific index in the
existing tuple we need to create a new tuple by
slicing the existing tuple and copying contents from
it.
Suppose we have a tuple i.e.
# Create a tuple
tupleObj = (12 , 34, 45, 22, 33 ,19)
As indexing starts from 0 in tuple, so to insert an
element at index n in this tuple, we will create two
sliced copies of existing tuple from (0 to n) and (n to
end) i.e.
# Sliced copy containing elements from 0 to n-1
tupleObj[ : n]
# Sliced copy containing elements from n to end
tupleObj[n : ]
Now join these two sliced copies with new elements
in between i.e.
n=2
# Insert 19 in tuple at index 2
tupleObj = tupleObj[ : n ] + (19 ,) + tupleObj[n : ]
Now contents of tuple will be.
(12, 34, 19, 45, 22, 33, 19)
A new Element is inserted at index n.
Modify / Replace the element at specific index in
tuple
To replace the element at index n in tuple we will
use the same slicing logic as above, but we will slice
the tuple from from (0 to n-1) and (n+1 to end) i.e.
# Sliced copy containing elements from 0 to n-1
tupleObj[ : n]
# Sliced copy containing elements from n to end
tupleObj[n + 1 : ]
None of the above sliced copies contains existing
element at index n. Now join these two sliced copies
with new elements in between i.e.
tupleObj = (12, 34, 19, 45, 22, 33, 19)
n=2
# Replace the element at index 2 to 'Test'
tupleObj = tupleObj[ : n] + ('test' ,) + tupleObj[n + 1 : ]
Now contents of tuple will be.
(12, 34, 'test', 45, 22, 33, 19)
Element in index n is replaced now.
Delete an element at specific index in tuple
To delete the element at index n in tuple we will use
the same slicing logic as above, but we will slice the
tuple from from (0 to n-1) and (n+1 to end) i.e.
# Sliced copy containing elements from 0 to n-1
tupleObj[ : n]
# Sliced copy containing elements from n to end
tupleObj[n + 1 : ]
None of the above sliced copies contains existing
element at index n. Now join these two sliced copies
i.e.
tupleObj =(12, 34, 'test', 45, 22, 33, 19)
n=2
# Delete the element at index 2
tupleObj = tupleObj[ : n ] + tupleObj[n+1 : ]
Now contents of tuple will be.
(12, 34, 45, 22, 33, 19)
Element in index n is deleted now.
//program
tupleObj = (12 , 34, 45, 22, 33 )
print("****** Append an element in Tuple at end
******")
print("Original Tuple : ", tupleObj)
# Append 19 at the end of tuple
tupleObj = tupleObj + (19 ,)
print("Modified Tuple : ", tupleObj)
print("******* Insert an element at specific index in
tuple *******")
print("Original Tuple : ", tupleObj)
n=2
# Insert 19 in tuple at index 2
tupleObj = tupleObj[ : n] + (19 ,) + tupleObj[n : ]
print("Modified Tuple : ", tupleObj)
print("******* Modify / Replace the element at specific
index in tuple *******")
print("Original Tuple : ", tupleObj)
n=2
# Replace the element at index 2 to 'Test'
tupleObj = tupleObj[ : n] + ('test' ,) + tupleObj[n + 1 : ]
print("Modified Tuple : ", tupleObj)
print("******* Delete the element at specific index in
tuple *******")
print("Original Tuple : ", tupleObj)
n=2
# Delete the element at index 2
tupleObj = tupleObj[ : n ] + tupleObj[n+1 : ]
print("Modified Tuple : ", tupleObj)
Adding/Inserting items in a Tuple
You can concatenate a tuple by adding new items
to the beginning or end as previously mentioned;
but, if you wish to insert a new item at any location,
you must convert the tuple to a list.
Example
Following is an example of adding items in tuple −
s= (2,5,8)
# Python conversion for list and tuple to
one another
x = list(s)
print(x)
print(type(x))
# Add items by using insert ()
x.insert(5, 90)
print(x)
# Use tuple to convert a list to a tuple
().
s_insert = tuple(x)
print(s_insert)
print(type(s_insert))
Output
we get the following output of the above code.
[2, 5, 8]
class 'list'>
[2, 5, 8, 90]
(2, 5, 8, 90)
class 'tuple'>
Using append() method
A new element is added to the end of the list using
the append() method.
Example
Following is an example to append an element
using append() method −
# converting tuple to list
t=(45,67,36,85,32)
l = list(t)
print(l)
print(type(l))
# appending the element in a list
l.append(787)
print(l)
# Converting the list to tuple using
tuple()
t=tuple(l)
print(t)
Output
Following is an output of the above code
[45, 67, 36, 85, 32]
class 'list'>
[45, 67, 36, 85, 32, 787]
(45, 67, 36, 85, 32, 787)