Python Tuple


In this function we will go through the Python tuples. We will also learn how to create tuples, and how to use them.

A tuple is similar to a list in Python. The difference between a tuple and a list is that the tuple is not mutable that is we cannot change the elements of the tuple once a tuple is defined whereas; the items of the list can be changed.

 

Advantages of Tuple over Lists

A tuple is similar to a list and hence both can be used in a situation. But there are some of the advantages of tuple over list that are listed below:

  1. Tuples are generally used for different data types on the other hand lists are used for items of same data type.
  2. As we cannot change the items in a tuple that is tuples are immutable therefore, the iteration through tuples is faster than lists. Because of this reason there is a minor difference in the speed of the two sequences.
  3. Tuples can be used as key for dictionary in Python because they are immutable and a key for a dictionary cannot be changed. We cannot do this with list of elements.
  4. If the user wants to protect his data then he should used tuples because tuples do not allow changing in the data.

 

Creating a Tuple

In Python programming language we can create a tuple by placing the items or elements within parenthesis. The items in a tuple are separated by comma. To create a tuple in Python parenthesis are optional but to use parenthesis is a good practice. A tuple in Python can have a number of items and these items can be of any data type such as float data type, integer, string etc.

Consider the following example, in which we have created tuple:

CODE

>>> myTuple = ()

>>> print (myTuple)

>>> myTuple = (1, 2, 3)

>>> print (myTuple)

>>> myTuple = (2, “Python”, 2.3)

>>> print (myTuple)

>>> myTuple = (“Python”, [1, 2, 3], (2, 4, 6))

>>> print (myTuple)

OUTPUT

()

(1, 2, 3)

(2, ‘Python’, 2.3)

(‘Python’, [1, 2, 3], (2, 4, 6))

python

In the above example, firstly we created a tuple as:

myTuple = ()

It can be seen clearly that this tuple is an empty tuple. Then we printed this tuple. Again a new tuple is created that has integer number; all the items of this tuple are of same data type.

Then a tuple is created which has its elements of different data types. The first element is an integer, the second element is a string and the third element is a floating point number.

After this we created a nested tuple that is a tuple inside another tuple.

In Python a tuple with only one item can be created but the user should put a comma after that single element to indicate to the Python interpreter that this is a tuple. The item of this type of tuple is also written inside parenthesis.

Consider the following example in which we have created a tuple which has only one element:

CODE

>>> myTuple = (“Python”)

>>> print (type(myTuple))

>>> myTuple = (“Python”,)

>>> print (myTuple)

>>> print (type (myTuple))

>>> myTuple = “Python”,

>>> print (type (myTuple))

OUTPUT

<class ‘str’>

(‘Python’,)

<class ‘tuple’>

<class ‘tuple’>

class-tuple

In the above example, first we have created a tuple in which we inserted only one item and also did not put any comma after that item, then we determined the type of the tuple by using the type () function in the print statement. The class of the tuple is printed and we observed that this is not a tuple rather this only a string.

Then we put a comma after that single element of the tuple and determined the class of the tuple by using the type () function. This time we found out that we defined a tuple with single element correctly. In the next statements we created a tuple, this time we did not add any parenthesis but comma is used after the single element of the tuple and the tuple worked.

 

Accessing Elements in a Tuple

In Python programming language we can access the elements of the tuple by using the some of the following ways:

 

Indexing

To access any element of the tuple we can use the index operator that is []. The index of the tuple is started from 0. Therefore, a tuple that has 5 elements will have the index from 0 to 4. If the user enters the index number after that the interpreter will generate an IndexError.

To access an element the index should be an integer and not a floating point number or of other data type. If the index is of other data type then the interpreter will generate a TypeError.

Similarly we can access the elements of nested tuple by using nested indexing. Consider the following example in which we have done so:

CODE

>>> myTuple = (‘e’, ‘r’, ‘t’, ‘a’, ‘w’, ‘q’)

>>> print (myTuple [0])

>>> print (myTuple [3])

>>> print (myTuple [6])

>>> print (myTuple [3.5])

>>> myTuple = (“Python”, [2, 4, 6], (1, 2, 3))

>>> print (myTuple [2][2])

>>> print (myTuple [1][1])

OUTPUT

e

a

Traceback (most recent call last):

  File “<pyshell#59>”, line 1, in <module>

    print(myTuple[6])

IndexError: list index out of range

Traceback (most recent call last):

  File “<pyshell#60>”, line 1, in <module>

    print (myTuple[3.5])

TypeError: list indices must be integers or slices, not float

3

4

4

In the above example a tuple is created and we used the index to access the elements of the tuple, when we used an index that is not in range with our tuple an error will be generated by interpreter and this will be index error. Then we used the index that is not an integer and again an error is generated by interpreter and this time the error is type error.

In the last lines a nested tuple is created and we used nested indexing to access the elements of the tuple that is inside another tuple. In the example when we used myTuple [2][2], we mean that the element 3 of the outside tuple and the element 3 of the inside tuple. As the index starts from 0 therefore, index 2 means the element 3.

 

Negative indexing

In Python we can use the negative indexing to access the elements of sequences. For example the index -1 refers to the last item of the sequence and index -2 refers to the second last element of sequence. Consider the following example in which we have done the negative indexing:

CODE

>>> myTuple = (‘e’, ‘r’, ‘t’, ‘a’, ‘w’, ‘q’)

>>> print (myTuple [-1])

>>> print (myTuple [-3])

OUTPUT

q

a

a

In the above example when we used -1 as index the last item of tuple that is q is printed, and when we used -3 as index the third last item of the index is printed.

 

Slicing

A slicing operator that is colon (:), is used to access a range of items in a tuple.

Consider the following example in which we have used the slicing operator to access a number of elements from a tuple:

CODE

>>> myTuple = (‘e’, ‘r’, ‘t’, ‘a’, ‘w’, ‘q’)

>>> print (myTuple [1:4])

>>> print (myTuple [:4])

>>> print (myTuple [4:])

>>> print (myTuple [:])

OUTPUT

(‘r’, ‘t’, ‘a’)

(‘e’, ‘r’, ‘t’, ‘a’)

(‘w’, ‘q’)

(‘e’, ‘r’, ‘t’, ‘a’, ‘w’, ‘q’)

tuple

In the above example, a tuple of items was created having 6 items that is from the index 0 to index 5. The first print statement displays the items from the index 1 to the index 4 and r, t, and a are printed because they fall in the corresponding category.

In the second print statement, the items from index 0 to index 4 are printed. In the third print statement the items from index 5 to end are printed. And in the last print statement all the items of the list are printed when we used only the slicing operator in the square brackets.

It can be seen that we only used the slicing operator to print all the items of the tuple.

 

Changing a Tuple

The elements of tuple cannot be changed that is tuples are immutable we cannot add or remove any item from a tuple unlike lists. But if the element inside a tuple is mutable that is of some data type that can be changed then we can change a tuple. This data type can include a list that is a nested tuple will have a list as its element so we can change or alter the elements of the tuple.

Consider the following example, in which we have changed the elements of a tuple when the element was a list:

CODE

>>> myTuple = (2, 3, 4, [2,4])

>>> print (myTuple[3][1])

>>> myTuple [3][1] = 5

>>> print (myTuple)

>>> myTuple [2] = 1

OUTPUT

4

(2, 3, 4, [2, 5])

Traceback (most recent call last):

  File “<pyshell#82>”, line 1, in <module>

    myTuple[2] = 1

TypeError: ‘tuple’ object does not support item assignment

typeerror

In the above example, a tuple is created and we first printed the second element inside the 3rd element of the tuple then we changed that element and printed the tuple, it worked successfully. When we tried to change the second element of the tuple we got an error, this is because of the data type of the element, the previous element was changed successfully because it was a list and lists are immutable.

In Python to combine or join or concatenate two tuples we use the + operator. This called concatenation. In Python tuple the items or elements can be repeated a number of times by using the * operator. In this way we will got a new tuple.

Consider the following example in which we have used the + and * operators to generate a new tuple:

CODE

 >>> print((2,4,6)+(8,10,12))

>> print((“Python”,) * 2)

OUTPUT

(2, 4, 6, 8, 10, 12)

(‘Python’, ‘Python’)

two-tuples

In the above example, two tuples are joined using the + operator and then the newly created tuple is printed. In the second print statement, the tuple that as a string as its element is repeated 2 times using the * operator, and in this way a new tuple is created and printed.

 

Deleting a Tuple

As the tuple is immutable therefore, we cannot change any item of the tuple or we cannot delete or remove any item of the tuple. But the entire tuple can be deleted by using the del keyword.

Consider the following example, in which we have deleted the entire tuple by using the del keyword:

CODE

>>> myTuple = (‘e’, ‘r’, ‘t’, ‘a’, ‘w’, ‘q’)

>>> del myTuple[2]

>>> del myTuple

>>> myTuple

OUTPUT

Traceback (most recent call last):

  File “<pyshell#86>”, line 1, in <module>

    del myTuple[2]

TypeError: ‘tuple’ object doesn’t support item deletion

Traceback (most recent call last):

  File “<pyshell#88>”, line 1, in <module>

    myTuple

NameError: name ‘myTuple’ is not defined

mytuple

In the above example, a tuple named myTuple is created and we tried to delete the element 3 in the tuple but an error was generated because tuples are immutable. Again we deleted the entire tuple by using the keyword del, the tuple is deleted and we tried to print that tuple an error was generated by the interpreter that this tuple is not defined. It means that we successfully deleted the tuple.

 

Python Tuple methods

In Python there are only two methods to be used with tuples. The methods to add or remove items in a tuple are not defined because tuples are immutable. The following are the two methods used with tuples in Python:

Method Description
count (x) This method is used to return the number of items that is equal to the variable x.
index (x) This method is used to return the first item of the list that will be equal to x.

Consider the following example, in which we used the tuple methods:

CODE

>>> myTuple = (‘e’, ‘r’, ‘t’, ‘a’, ‘w’, ‘q’)

>>> print(myTuple.count(‘t’))

>>> print(myTuple.index(‘r’))

OUTPUT

1

1

1

In the above example, the count function is used to determine that how many times an item is appeared in the tuple. The index function is used to find out that where the particular item of the tuple is located inside the tuple.

 

Other Tuple Operations

 

Tuple Membership Test

In Python we can test an item in the tuple by using the keyword in. By testing an item in the tuple we mean that if the item exists in the tuple or not.

Consider the following example in which we have declared a tuple and checked if any item of the tuple exists in the declared list or not by using the in keyword Python:

CODE

>>> myTuple = (‘e’, ‘r’, ‘t’, ‘a’, ‘w’, ‘q’)

>>> print (‘e’ in myTuple)

>>> print (‘t’ in myTuple)

>>> print (‘s’ in myTuple)

OUTPUT

True

True

False

false

In the above example a tuple named myTuple is created that has characters and used the in keyword in the print statement to check if the item exists in the tuple or not. If the item is found in the tuple True will be returned by the interpreter and False if the item is not found in the tuple.

 

Iterating Through a Tuple

In Python we can iterate through each item of the tuple by using the ‘for statement’. Consider the following example in which we have used the ‘for statement’ to iterate through the items of the tuple:

CODE

>>> for desert in (‘Custard’, ‘Trifle’, ‘Pie’):

          print(“I like to eat”, desert)

OUTPUT

I like to eat Custard

I like to eat Trifle

I like to eat Pie

i-like-to-eat-pie

In the above example, we have used ‘desert’ as the counter variable to iterate through the tuple and then printed the tuple using the counter variable.

 

Built in Functions to Tuple

In Python there are many built in functions such as all (), len (), min () etc. Consider the following table in which we have described the commonly used functions in Python for tuples:

Function Description
all () This function is used to return a true if all the elements in the tuple are true and if the tuple is empty.
any () This function is used to return a true if any of the elements in the tuple are true and returns a false if the tuple is empty.
enumerate () This function is used to return an enumerate object. The enumerate function has the index and the value of all the items of the tuple as a pair.
len () This function is used to return the length of the tuple or the number of the elements in the tuple.
max () This function is used to return the largest item in the tuple.
min () This function is used to return the smallest item of the tuple.
sorted () This function is used to a new sorted tuple. The sorted () function does not sort the tuple itself but it returns the already sorted tuple.
sum () This function is used to return the sum of all the elements in the tuple.
tuple () This function is used to an iterables such as list, string, dictionary or a set to a tuple.