Python 3 Data Types – Tuples – Explanation with examples

A Tuple in Python, much similar to a list, is an immutable data type which acts as a container and holds different objects together in an order.

A tuple acts as a collection of objects and is itself immutable, i.e., the tuple can’t be modified once it is created. A tuple can be used to store integers or any other data types together in an order. e.g. (‘a’, ‘b’, ‘c’, ‘f’), (2, ‘abcdef’, [9,7,3,5], 10) etc.


Creating a tuple (Initialization) –

A tuple is initialized by placing different objects as elements under parentheses “( )”.  However, the parentheses are not necessary. They can be created even without them, but it’s a good practice to use them.

Data at the ith index can be accessed by using tuplename[i]. Here tuplename is the name of the tuple and ‘i’ is the index which has to be accessed.

The index number of lists starts from zero and goes up to n-1, where n is the number of elements in the tuple. Elements inside lists can be modified, but the same is not applicable for tuples.

Some examples will clear this up-

a=(2,'yes',4,'no',6)
print(a)
print(a[0])
a[2]=9   #Value cannot be change. Runtime Error Occurs
print(a[2])
print(a)
Output:-
(2, 'yes', 4, 'no', 6)
2

The Output was terminated. This program caused Runtime Error because we tried to change the element in the tuple. This shows that tuple is immutable, whereas lists are mutable.

Printing a would print the whole tuple whereas printing a[i] would print the element at the ith index. Tuples have almost the same property as that of lists. But lists are mutable whereas tuples are not. This can be seen as a[2] was not changed from 4 to 9, and the output confirms it with an error.


Indexing and Negative Indexing –

The indexing can also be done from the last index. If we want to access the elements from the reverse order, we use this method. The last index is -1, second last is -2, and so on. Some examples will clear this up-

a=(2,'yes',4,'no',6)
print(a)
print(a[3])
print(a[-1])
print(a[-4])
Output:-
(2, 'yes', 4, 'no', 6)
no
6
yes

Slicing and Negative Slicing–

Python tuples have a special advantage of slicing in which a portion or a section of a list can be simply obtained without any trouble. Taking a look at the following example –

a=(1,3,4,5,6,8)
print(a[0:3]) #This prints elements with indices 0,1,2

print(a[:5]) #Similarly, upto indices less than 5, i.e. 0,1,2,3,4

print(a[1:2]) #Only index 1

print(a[2:]) #Starting from index 2, to the length of list
Output:-
(1, 3, 4)
(1, 3, 4, 5, 6)
(3,)
(4, 5, 6, 8)

From the above example, you can see that

  1. if we print a[i:j], the output would be the elements from index i to index j-1.
  2. for a[i:] the output would be from index i to last element and
  3. for a[:j], it will be from 0th index to index j-1.

This simple feature of tuples is called slicing. Similarly, negative slicing in tuples can be cleared out from this example –

a=(1,3,4,5,6,8)
print(a[-1]) #prints 1st element from the reverse direction
print(a[-4])
print(a[-4:-2]) #prints the 4th and 3rd element from the last, i.e. indices 2,3
print(a[-5:])
Output:-
8
4
(4, 5)
(3, 4, 5, 6, 8)

From the above example, you can see that if we print a[-i], the output would be the i th element  from the end of the list. Slicing is just as the same, but just with negative indices.

Apart from the mutable/immutable difference, Lists and Tuples have one more thing that’s different. Tuples can be used as a key in a Dictionary, whereas Lists cannot. Can you guess why? This is because of immutability of tuples once they are created they can not be changed and hence a perfect candidate to be selected as a key.  Here’s an example –

a=(2,3)
d={}
d[a]=1 # Tuple as a key
print(d[a])
Output:-
1
a=[2,3]
d={}
d[a]=1 # List as a key
print(d[a])

The Output is terminated and Run Time Error occurs in this program. This is one of the major difference between a list and a tuple.

Use of the functions like max, min, len, cmp etc. is the same as that for lists. Iterating over tuples is also the same, provided that the content of the tuple is not being modified/deleted. Any modification/update or deletion process performed in tuples would result in Runtime Error.

That’s all for this tutorial. If you have any doubts, please post them in the comments section. Any ideas/suggestions are welcome.
Do not forget to share, like and spread the knowledge. :)

  • Phillip Bailey

    Thanks for the article. It’s very concise and helpful. I think you have an error in the output in the Indexing and Negative Indexing section, though. Shouldn’t a[-1] be 6 and not 2?

    • hiteshgarg21

      Thanks @disqus_QImYneteWf:disqus for pointing it out. Changes are done.

  • ddorian43

    >>holds different immutable objects
    Nope. Is itself immutable. Example you put a dict inside a tuple and the dict can still change.

    • hiteshgarg21

      Hi @ddorian43:disqus, Thanks for pointing out. I have updated that. Please check it out.

  • John Strickler

    While everything you said is true, most of it could apply to lists, strings, and bytes just as easily. Rather than thinking of a tuple as a restricted list, it’s best to think of it as a “record” or “struct” — a fixed-size collection of related data.

    Thus, it is common to have a list of tuples representing a dataset. This list of tuples is analogous to a database table. The list is the table, and each tuple is a row in the table.

    A very important operation on tuples is unpacking, which means copying the tuple to variables. While not so interesting for a single tuple, it’s very useful for an iterable of tuples.

    data = [
    ('red', 5),
    ('blue', 10),
    ('purple', 9),
    ]

    for color, number in data:
    print(color, number)

    The for loop unpacks each tuple into the variables color and number.