Python Tuple

Python Tutorial: Python Tuple, Tuple in Python, Python Tutorial Awesome 20 min Guide.

topictrick
topictrick
A Python tuple is a Python sequence. They are generally used to store a group of elements, which do not change throughout the program. Since tuples are immutable, so you can only use a basic set of functions/methods such as len, max, min, sort, index, count. But you can append or change a tuple by using programming techniques. Let's go through all these techniques and code snippets in this Python tutorial.

Table of Contents

Introduction.

Welcome back to another exciting tutorial on “Python Tuple”. In this python tutorial, you’ll learn the basics and characteristics of Tuples in Python. You’ll learn how to create or manipulate a tuple in python.
You’ll also learn the practical implementation of the tuple, in Python programs. After, completing the tutorial you will have a good understanding of tuple basics, tuple functions and, tuple methods. Let’s start with the tutorial.

What is a Tuple in Python?

A Python Tuple is a sequence data structure, which stores a group of items or elements. Tuples are generally used to store constant values. The values that should not change during the program and can be retrieved when needed.

To create a tuple in python, you need to including elements between parentheses i.e. (). All the tuple elements should be separated by a comma “,”.

Tuple Example: a_tpl = (1, 2, 3, 4, 5).

Tuple in Python
Tuple in Python

Python Tuple Vs List.

Python tuple is like a list in regards to functionality but there is a big difference in properties. The following are the basic difference between python tuple and list.

Python Tuple Python Lists
A Tuple is immutable.
The List is mutable.
A tuple is created by using parentheses i.e.().
A list is created by using square brackets i.e. [].
Tuple Functions: Len, Min, Max, Sorted, Index, and Count.
List Functions: append, pop, reverse, count, index, min, max, Glen, sort, count, copy, extend, reverse, sum, and clear.

How to create Tuple in Python?

You can create tuple in python by writing elements between parentheses i.e. (). All tuple elements should be separated by a comma “,”.

You can store different types of items in the tuples. The following are a couple of examples to create Tuples in Python.

# Create an empty tuple.
a_tpl = ()                
# Assign integer items to a tuple.
b_tpl = (1, 2, 3, 4)  
# Assign character items to a tuple.
c_tpl = ('a', 'b')       
# Assign homogenous items to a tuple.
d_tpl = ('a', 'topictrick.com', 1)
# Nested Tuple in Python.
n_tpl = (1, 2, ('a','b'))

You can create a tuple without parentheses by writing element delimited by a comma “,”. Let’s look at a couple of examples below.

# Create Python Tuple without parentheses.
e_tpl = 1, 2, 3, 4

Important Point: The point to remember is that if do not use brackets, it will become a tuple and not a list or any other datatype.

What is Python Tuple() Function?

Python tuple function is a built-in function. Tuple function converts the passed value into a tuple. The following example converts the list into a tuple.

# Create tuple by using Python Tuple Method.  
a_lst = [1, 2, 3, 4 ,5]
g_tpl = tuple(a_lst)
print("Tuple Value :", g_tpl)
#Output:
Tuple Value : (1, 2, 3, 4)

Another way to create a tuple is by using range() function. Let’s create a tuple that contains the number from 0 to 9.

# Create tuple by using Python range() function.
g_tpl = tuple(range(10))
print("Tuple :", g_tpl)
#Output:
Tuple : (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

How to access the elements of the tuples in Python?

You can access the elements from a tuple by using an indexing or slicing method.

Indexing represents the position of an element in a tuple. You can use either a positive index or negative index to access the tuple element.

Remember, in python positive index starts from 0 and the negative index starts from -1.

Let’s see a couple of Python tuple examples.

# Consider a_tpl is a tuple.
a_tpl = (1, 2, 3, 4, 5, 'topictrick')
# Positive Index. 
a_tpl[0]         # print first element.
a_tpl[5]         # print last  element.
#output.
1
topictrick
# Negative Index. 
a_tpl[-6]        # print First element.
a_tpl[-1]        # print Last  element.
#output.
1
topictrick

The slicing technique extracts a piece of the tuple. Python slicing generally needs three-parameter i.e.[start, end, step-size]. Let’s see a couple of examples to understand the slicing technique.

# Consider b_tpl is a tuple. 
b_tpl = (1, 2, 3, 4, 5)
# print all items.
print('All items of tuple :', b_tpl[:])     
# Output. 
All items of tuple : (1, 2, 3, 4, 5)
# print first two elements of a tuple.
print('First two element of a tuple :', b_tpl[0:2]) 
# Output.
First two elements of a tuple : (1, 2)
# print last two elements of tuple.
print('Last two element of tuple :', b_tpl[3:5]) 
# Output.
Last two elements of a tuple : (4, 5)

Python Tuple Methods.

There are few functions provided in Python to perform basic operations on the tuple. These tuples functions are mention in the table below:

Python Tuple Method Description
len()
Returns the count of the element in the tuple.
min()
Returns the smallest element in the tuple.
max()
Returns the largest element in the tuple.
count()
Returns how many times the element 'y' found in a tuple.
index()
Returns the index of the element.
Now, let’s look at various python tuple example. These examples show the practical usage of tuple methods.
# r_tpl is a tuple. 
r_tpl = (1, 2, 3 ,4 , 5, 6)
# Python Tuple len function. 
print('Lenght of the tuple:', len(r_tpl))
# Output.
Lenght of the tuple: 6
# Python Tuple Min function. 
print('Min Value of the tuple:', min(r_tpl))
# Output.
Min Value of the tuple: 1
# Python Tuple Max function. 
print('Max Value of the tuple:', max(r_tpl))
# Output.
Max Value of the tuple: 6
# Python Tuple Count function. 
print('Element occurrence count:', r_tpl.count(1))
# Output.
Element occurrence count: 1
# Python Tuple index function. 
print('Element Index:', r_tpl.index(1))
# Output.
Element occurance count: 0

Python Tuple Operations : Insert, Append, Del and Modify.

Since tuples are immutable. You cannot change the elements of tuples once it is assigned to a tuple literal.

But there is a way through which you can append, remove, insert the item to a tuple.

To manipulate data in a tuple, you can convert tuple into a list by using lists() function.

Perform the required operation (i.e. append, remove, insert, sort, reverse, etc.) and convert the list into tuple by using tuple() function.

The following example shows how the item is appended to a tuple.

# Python tuple append method. 
a_tpl = (1, 2, 3, 4, 5)
a_tpl
# output.
(1, 2, 3, 4, 5)
# Convert Python tuple to a Python list.
tmp_tpl = list(a_tpl)
tmp_tpl
# output.
[1, 2, 3, 4, 5]
# append new item to a list. 
tmp_tpl.append(40)
tmp_tpl
# Output.
[1, 2, 3, 4, 5, 40]
# Convert list into a tuple. 
a_tpl = tuple(tmp_tpl)
a_tpl
# Output. 
(1, 2, 3, 4, 5, 40)
# Delete tuple.
del(a_tpl)
# Sort tuple.
print("Sorted Tuple:", sorted(a_tpl))
output. 
Sorted Tuple: (1, 2, 3, 4, 5)

Python Tuple Unpacking and Packing.

Python Tuple unpacking
Python Tuple unpacking

Python tuple packing and unpacking is a technique of mapping tuple elements. When you assign a group of elements to a tuple literal is know as python tuple packing.

But, when you assign a group of the object to the same tuple literal, then it will map all group items. Let’s go through the example for better understanding.

# Python Tuple Packing. 
cptl_tpl = ('Dublin','London','Berlin')   
print('Capital City:', cptl_tpl)
# Output. 
Capital City: ('Dublin','London','Berlin')
# Python Tuple Unpacking.
(cpt1,cpt2,cpt3) = cptl_tpl  
print('Ireland Capital is:', cpt1)
print('UK      Capital is:', cpt2)
print('Germany Capital is:', cpt3)
# Output. 
Ireland Capital is: Dublin
UK      Capital is: London
Germany Capital is: Berlin

Important Point: The number of tuple element and objects should be the same for python packing and unpacking functions.

Topictrick Youtube Channel.

This Python tutorial is linked to youtube video tutorials. It's recommended to watch the video tutorial. This tutorial video tech the basics of tuples in Python and live coding demo. You'll also learn the practical implementation of all tuple functions.

Summary.

Finally, at the end of the Python tuple tutorial. Let’s summarised what we learn today. Tuples in Python are similar to lists with the difference that tuples are immutable. whereas lists are mutable. Since a tuple is immutable, once you create a tuple, you cannot modify its elements.

If you like our tutorial, then please don’t forget to subscribe to our youtube channel and share the post with your friends.