Python Tuples Tutorial

Python Tuples Tutorial – Learning Python Tuples with Example

Common Python Tuples interview questions and doubts

Hi there! Hope you are doing well. In this article, we will learn Python Tuples and will understand some Python Tuples concepts through examples. If you don’t know –  what is the Python programming language? its usage and benefits. I recommend you go through all about the Python programming language guide. If you are already familiar with Python and you just want to refresh the Python Tuples understanding you are at the right place. Moreover, this article will also help you get prepared with Python tuples interview questions.

Without wasting any time let’s dive in.

What are Python Tuples?

The Tuple is a data structure in Python, with a datatype of “tuple”. The Tuples is an immutable(i.e. unchangeable) ordered sequence of data. Tuple elements/items are ordered, meaning each element has a defined position that will not change. Immutable means that once the tuple is created, we cannot change, add or remove items to or from the Tuple.

A Python tuple is a collection of data/items written with a round bracket separated by commas. A Tuple can hold data types like integers, strings, floats, and objects. It can also hold different data types at the same time.

 
Each data in the tuple is referred to as elements or items which are indexed. The tuple index count starts from 0. Python Tuple also allows duplicate elements, since each element will have its own index position and credibility. Tuples are created using round brackets () or tuple() Python constructor.

Difference between Python Tuples and Python List?

TuplesList
ImmutableMutable
More memory efficient Less memory efficient
Items are closed by a round bracket Items are closed by a square bracket 
Smaller size thus fasterSlight bigger in size hence slightly slower

How to create and get the length of Python tuples?

A Tuple can be created using a round bracket or by using a tuple() constructor. 

#tuple creation using ()
state_tuple1 = ("Goa","Kerala","Panjab","Delhi")
print(state_tuple1)
 
#tuple creation using tuple() constructor
state_tuple2 = tuple(("Karnataka","Gujarat","Tamilnadu","Uttrakhand"))
print(state_tuple2)
 
#Multi data type tuple
multi_data_type_tuple = ("Karnataka",8,"Uttrakhand",98.3,{"Goa"})
print(multi_data_type_tuple)

The length of a Tuple can be found by using the len() built-in function.

state_tuple = ("Goa","Kerala","Panjab","Delhi")
print(len(state_tuple))

How to access Python tuples?

1. Positive indexing

As we mentioned above Tuple items are indexed i.e. each element of the Tuple has a unique index number. Using this index number (positive number) a specific item from the Tuple can be retrieved. This method is also known as positive indexing i.e. accessing the Tuple from the beginning. So 0 will refer to the first item, 2 will refer to the third item, and so on.

state_tuple = ("Goa","Kerala","Panjab","Delhi")
print(state_tuple[0])
print(state_tuple[2])

2. Negative indexing

A Tuple can also be accessed using negative indexing i.e. negative number. Negatives here indicate that a tuple will be accessed from the end. NOTE: In negative indexing, numbers start from -1, unlike 0 in positive indexing. So, here -1 means the last item, and -2 means the second last item.

state_tuple = ("Goa","Kerala","Panjab","Delhi")
print(state_tuple[-1])
print(state_tuple[-2])

3. Range of Indexes

This method is used to access a range of tuple items at once, unlike the above method where we access one item at a time. To get a range of values one can set the start to one index number and the end to another index number.

In range indexing access methods, if you miss the start index then you will get the range from the start of the tuple to the specified end index number. If you miss out on the end index then you will get a range from the start index number till the end of the tuple. 

NOTE: In the positive range index, you will get items from startIndex to endIndex-1.

#Positive range index example
state_tuple = ("Goa","Kerala","Panjab","Delhi","Karnataka","Gujarat","Tamilnadu")
print(state_tuple[2:4])
print(state_tuple[:2])
print(state_tuple[4:])

NOTE: In the negative range index, you will get items from -ve startIndex to -ve endIndex-1.

#Negative range index example
state_tuple = ("Goa","Kerala","Punjab","Delhi","Karnataka","Gujarat","Tamilnadu")
print(state_tuple[-4:-2])
print(state_tuple[:-2])
print(state_tuple[-4:])

How to update Python Tuples?

Change tuples values:

Interview question – can you change the tuple values? If Yes, how?

As we discussed above, tuples are immutable or unchangeable. So once a tuple is created we can’t change its value. But there is one way to do it.

First, convert the tuple to a list. Then change the value in the list. Finally, convert the updated list back to the tuple.

#Update Tuple
state_tuple = ("Goa","Kerala","Karnataka")
state_list = list(state_tuple)
state_list[1] = "Gujarat"
state_tuple = tuple(state_list)
print(state_tuple)

Add items to tuples:

For this too, you can use the above-mentioned methods. First, convert a tuple to a list, then use the append() method to add value to the list. Finally, convert back the list to the tuple.

#Add item to Tuple Example
state_tuple = ("Goa","Kerala","Karnataka")
state_list = list(state_tuple)
state_list.append("Delhi")
state_tuple = tuple(state_list)
print(state_tuple)

Hold on, there is one more way. Tuple does not allow you to add items to tuple but Python Tuple does allow you to add tuple to tuple.

state_tuple = ("Goa","Gujarat","Karnataka")
new_tuple = ("Kerala","Punjab")
state_tuple = state_tuple + new_tuple
print(state_tuple)

Interview question – can we add value to a tuple? 

Yes, we can do it in two ways, first by converting the tuple to a list and then adding value. Second, by creating a tuple with a new value and then adding this tuple to the existing tuple.

How to unpack python tuples?

First and foremost, what is unpacking in Python? An operation to extract value from an iterable (tuple or list) and assign it to variables. The variables should also be in lists or tuples. There should be the same number of variables or one should use * to handle unassigned values.

#packing a tuple
state_tuple = ("Goa","Gujarat","Karnataka")
print(state_tuple)
#unpacking a tuple
(GA,GJ,KA) = state_tuple
print(GA,GJ,KA)

How to loop through Python tuples?

As we know we can use a for loop or while loop to iterate (loop) through any iterable. So, Tuple items can also be accessed using for loop and a while loop.

#for loop example
state_tuple = ("Goa","Kerala","Punjab","Delhi")
print(state_tuple)
for state in state_tuple:
   print(state)
 
print("\n")
 
#for loop using tuple index
state_tuple = ("Goa","Kerala","Punjab","Delhi")
print(state_tuple)
for i in range(len(state_tuple)):
   print(state_tuple[i])
 
#while loop using tuple index
state_tuple = ("Goa","Kerala","Punjab","Delhi")
print(state_tuple)
i=0
while i < len(state_tuple):
   print(state_tuple[i])
   i+=1

How to join Python tuples?

We have already used this operation above in adding an item to the tuple. So basically two or more tuples can be joined using the + operator.

#Join Tuple example
state_tuple1 = ("Goa","Gujarat","Karnataka")
state_tuple2= ("Kerala","Punjab")
state_tuple = state_tuple + new_tuple
print(state_tuple)

How to delete or remove items from Tuples?

As we know tuple is immutable, which means we can’t add an item to a tuple nor we can delete an item from the tuple. But there are several ways to do it. 

Using slicing:

We can use range index (slicing) on the tuple and then merge the tuple by using the + operator.

#slicing method to remove item from tuple
state_tuple = ("Goa","Gujarat","Karnataka","Kerala","Punjab","Delhi")
new_tuple = state_tuple[:3] + state_tuple[4:]
print(new_tuple)

Converting to List:

Here we first convert tuples to lists, then we use the remove() method to remove items from the list. There are other ways to remove items from the list you can use anything you want. After removing an item from the list, convert it back to the tuple.

#removing item from tuple by converting it to list
state_tuple = ("Goa","Gujarat","Karnataka","Kerala","Punjab","Delhi")
state_list = list(state_tuple)
state_list.remove("Karnataka")
state_tuple = tuple(state_list)
print(state_tuple)

How do multiply Tuples?

Multiplying a tuple basically means repeating each item of a tuple by N number of times.

#removing item from tuple by converting it to list
state_tuple = ("Goa","Gujarat","Punjab","Delhi")
state_tuple_2X = state_tuple * 2
print(state_tuple_2X)

Tuples Methods:

MethodExplanation
count()Return the number of times a species item present in a tuple
index()Return the position of the passed item in the parameter

Tuples Interview Questions

How to multiply a number with each tuple of items?

#multiply a number with value of tuple
number_tuple = (2, 5, 8, 1, 5, 3)
number = 2
result_tuple = tuple(v*number for v in number_tuple)
print(result_tuple)

How to multiply all integer values of a tuple?

#multiply all values of tuple
import math
number_tuple = (2, 5, 8, 1, 5, 3)
result = math.prod(number_tuple)
print(result)

How to add a number to each tuple item?

#add a number with value of tuple
number_tuple = (2, 5, 8, 1, 5, 3)
number = 5
result_tuple = tuple(v+number for v in number_tuple)
print(result_tuple)
 
 
#get sum of all tuple value
number_tuple = (2, 5, 8, 1, 5, 3)
result = sum(number_tuple)
print(result)

Check if Items are present/exist in Tuple

state_tuple = ("Goa","Kerala","Punjab","Delhi","Karnataka","Gujarat","Tamilnadu")
search_item = "Goa"
if search_item in state_tuple:
   print("Value present in Tuple")
else:
   print("Value not found in Tuple")

Create and Access a nested tuple

#nested tuple
state_tuple = (("Goa","Orange"),"Kerala",("Delhi","DL"),"Karnataka",("Gujarat","GJ",129),"Tamilnadu")
 
#accessing nested tuple
print(state_tuple[0][0])
print(state_tuple[2][1])
print(state_tuple[4][2])

Reverse item of tuple

#reverse item of tuple using slicing
state_tuple = ("Goa","Kerala","Punjab","Delhi","Karnataka","Gujarat","Tamilnadu")
print(state_tuple[::-1])

Above are the few interview questions that an interviewer asks. I will suggest you practice some more interview (medium and tough level) questions, you can take a look at these 25 Tuple questions. Another important thing is if you are preparing for your upcoming interview you should also refresh your knowledge on some basic python interview questions.

Hope I have made it easy to understand the Python tuple and its basic operations. If you Like this article and think it was easy to understand and might help someone you know do share it with them. Thank You! See you soon.

If you have any questions or comments feel free to reach me at.

Checkout out other python concept covered in Python Tutorial