Python Tuple Tutorial with Hands-on Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

Explore the concept of Tuple in Python and Tuple vs List in this tutorial with examples:

In Python, we have four collection data types as mentioned below:

  • List
  • Set
  • Dictionary
  • Tuple

In this tutorial, we will take an in-depth look at Tuple in Python and its various operations. Don’t miss out to read through our Entire Range of Python Tutorials.

In Python, the tuple is a data structure and is similar to an array which is used to store multiple data at once. If you have experience in other programming languages like Java, C, C++, etc. then you will be familiar with the concept of arrays, thus tuple is almost the same as arrays.

tuple in python

What is a Tuple?

A Tuple is a data structure that is employed to store multiple data at one time. The data stored in a tuple are heterogeneous and this indeed makes it the most powerful feature of the tuple in Python. We can store multiple data of different data types like String, Integers, and objects as well in a single tuple.

A tuple is immutable in Python, thus data cannot be changed once it’s assigned.

Data stored in a tuple are accessed using their index, for the tuple index will always start from Zero. Each element has a specific place in the tuple and all of those data are accessed with the help of the index.

Tuple vs List

  • List in Python is mutable (Values can be changed) whereas Tuple is immutable (Values cannot be changed)
  • When compared to the list data structure, tuple provides fewer features in Python.
  • As tuples are immutable, it increases the performance as iterating in a tuple is faster when compared to the list.

Creating a Tuple

Data in a tuple are stored with comma-separated and is enclosed in a bracket (). Tuples can contain any number of items of different types.

Syntax:

Tuple = (item1, item2, item3)

Example: 1

Tuple = ()

Example: 2

Tuple = (2, 4, 5.6)

Example: 3

Tuple = (2, 5, 4.5, “Hi”)

Example: 4

Tuple = (“Hi”, “Hello”, “Python”)

If we observe the above examples we have stored items of different data types with a comma-separated where 2 and 5 are of type Integer, 4.5 is of type float and ‘Hi’ is of type String. We can declare an empty tuple as well.

We can also declare a list or tuple inside a tuple, and this is called nested tuple.

Example: 5

 Tuple = (“Python”, [2, 4, 6], (4, 5.6, “Hi”))
print(“Contents of tuple is:”, Tuple)

Output:

Contents of tuple is: (‘Python’, [2, 4, 6], (4, 5.6, ‘Hi’))

If you observe the above example we have declared a list and tuple inside another tuple.

If the tuple contains only one element, then it’s not considered as a tuple. It should be a trailing comma to specify the interpreter that it’s a tuple.

Let’s see, in the below example

Example: 6

 my_tuple = (“Python”)
Print(“Type of my_tuple is:”, type(my_tuple))
my_tuple = (10)
Print(“Type of my_tuple is:”, type(my_tuple))
my_tuple = (“Python”, )
Print(“Type of my_tuple is:”, type(my_tuple))

Output:

Type of my_tuple is: <class ‘str’>
Type of my_tuple is: <class ‘int’>
Type of my_tuple is: <class ‘tuple’>

Accessing values in Tuple

There are several ways in which we can access the items present inside the tuple in Python. With the help of an index, we can access the elements of the tuple. The index starts at 0 and the index should always be an Integer. If we use an index other than an integer like float, then it will result in TypeError.

Example: 1

Tuple = (3, 5, 6.7, “Python”)
print(“Tuple is:”, Tuple)

Output:

Tuple is: (3. 5. 6.7, “Python”)

In the above example, we have directly printed the tuple using the print function, and we are not accessing the individual elements of the tuple.

Let’s access the individual elements of the tuple.

Example: 2

Tuple = (3, 5, 6.7, “Python”)
print(“Third element of the Tuple is:”, Tuple[2])

Output:

Third element of the Tuple is: 6.7

Example: 3

Tuple = (3, 5, 6.7, “Python”)
print(“First element of the Tuple is:”, Tuple[0])
print(“Last element of the Tuple is:”, Tuple[3])

Output:

First element of the Tuple is: 3
Last element of the Tuple is: ‘Python’

We can also access the items present in the nested tuple with the help of nested indexing.

Example: 4

Tuple = (“Python”, [2, 4, 6], (4, 5.6, “Hi”))
print(“First element of the tuple is:”, Tuple[0][1])
print(“Items present inside another list or tuple is:”, Tuple[2][1])

Output:

First element of the tuple is: ‘y’
Items present inside another list or tuple is: 5.6

As discussed in the Python List tutorial the values inside the nested list are stored in the form of a matrix, similarly, Tuple also follows the same concept.

P y t h o n

2 4 6

4 5.6 Hi

So, when we try access Tuple[0][1] then it will point to the 1st row and 2nd column so the data will be ‘y’.

Similarly, when we try to access List[2][1] then it will point to the 3rd row and 2nd column so, the data will be 5.6

Note: The above concept works only when you attempt to access the items of the tuple using the nested indexing.

Negative Indexing

We can access data using a negative index as well. A negative index will always start from -1 and -1 refers to the last element and -2 refers to the last second item and hence along.

Always remember that Positive indexing is used to iterate the items of a tuple in a forward manner, whereas negative indexing follows the backward manner.

Example: 1

Tuple = (3, 5, 7.8)
print(“Last element of the tuple is:”, Tuple[-1])

Output:

Last element of the tuple is: 7.8

Example: 2

Tuple = (3, 5, 7.8)
print(“First element of the tuple is:”, Tuple[-3])

Output:

First element of the tuple is: 3

Slicing the Tuple

Using the slice operator (:), we can access a range of elements from the tuple.

Example: 1

 Tuple = [1, 2.5, 3, 4.9, 5, 6, “Python”]
print(“Elements from 2nd to 5th is: ”, Tuple[1:5])
print(“Elements beginning to 4th is: ”, Tuple[:-3])
print(“Elements 4th to end is: ”, Tuple[3:])
print(“Elements from start to end is: “, Tuple[:])

Output:

Elements from 2nd to 5th is: (2.5, 3, 4.9, 5)
Elements beginning to 4th is: (1, 2.5, 3, 4.9)
Elements 4th to end is: (4.9, 5, 6, ‘Python’)
Elements from start to end is: (1, 2.5, 3, 4.9, 5, 6, ‘Python’)

We can also access the elements present in the tuple using for loop.

Example: 2

Tuple = (3, 5, 7.8)
print(“First element of the tuple is:”, Tuple[-3])

Output:

1
2
3.5
5
‘Hi’

Slicing the tuple

Changing a Tuple

As we know, Tuples are immutable in Python, hence data cannot be changed, but lists are mutable. Thus lists present inside tuples (nested tuple) can be changed.

Example: 1

 Tuple = (3, 4.5, [4, 5, 6])
print(“Original Tuple is:”, Tuple)
Tuple[2][0] = 2
print(“Updated Tuple is:”, Tuple)

Output:

Original Tuple is: (3, 4.5, [4, 5, 6])
Updated Tuple is: (3, 4.5, [2, 5, 6])

We cannot use append() or extend() function in the Tuple as tuples are immutable. Also, you cannot use remove () or pop () function as well.

Converting List to Tuple

We can convert a list into Tuple using a Python built-in function called tuple ().

Syntax:

tuple(arg1)

Tuple () function accepts one argument, and the argument should be the list variable name.

Example: 1

List = [2, 4, 5.6, “Hi”]
print(“Original List is:”, List)
Tuple = tuple(List)
print(“After converting to tuple is:”, Tuple)

Output:

Original List is: [2, 4, 5.6, “Hi”]
After converting to tuple is: (2, 4, 5.6, “Hi”)

Converting Tuple to String

We can also convert Tuple into String using 2 ways.

Approach: 1

Using the join() in-built method from String, we can convert Tuple into String.

Example: 1

 def convertTupleToString(my_tuple):
                           s = ‘’.join(my_tuple)
                           return s
Tuple = (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
print(“Before converting to String:”, Tuple)
str = convertTupleToString(Tuple)
print(“After converting to String:”, str)

Output:

Before converting to String: (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
After converting to String: ‘Python’

Approach: 2

reduce() method from the functools is used to convert Tuple into String. This method concatenates the character present in the tuple and produces a string.

Example: 2

import operator
import functools

def convertTupleToString(my_tuple):
           s = functools.reduce(operator.add, (my_tuple))
           return s

Tuple = (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
print(“Before converting to String:”, Tuple)
str = convertTupleToString(Tuple)
print(“After converting to String:”, str)

Output:

Before converting to String: (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
After converting to String: ‘Python’

Note: You can convert Tuple to String only if the Tuple contains characters. If the tuple contains any one item of type integer or float then it will throw an error.

Example: 3

 
def convertTupleToString(my_tuple):
           s = ‘’.join(my_tuple)
           return s
Tuple = (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, 4, 6.5)
print(“Before converting to String:”, Tuple)
str = convertTupleToString(Tuple)
print(“After converting to String:”, str)

Output:

Before converting to String: (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, 4, 6.5)
Traceback (most recent call last):
File “<pyshell#1>”, line 1, in <module>
str = ”.join(Tuple)
TypeError: sequence item 6: expected str instance, int found

Sort Tuple in Python

In python, we have an in-built function called sorted() to sort the elements of the tuple.

Syntax:

sorted(arg1)

The sorted() method accepts one argument which is a variable name.

Example: 1

 
def sortTuple(my_tuple):
              sort = sorted(my_tuple)
              return sort

Tuple = (2, 4, 6, 1, 4, 7.8, 2.7)
print(“Before sorting the Tuple is:”, Tuple)
sortedTuple = sortTuple(Tuple)
print(“After sorting the Tuple is:”, sortedTuple)

Output:

Before sorting the Tuple is: (2, 4, 6, 1, 4, 7.8, 2.7)
After sorting the Tuple is: [1, 2, 2.7, 4, 4, 6, 7.8]

Packing and Unpacking the Tuple

Python provides an important feature called packing and unpacking. In packing, we put the value into a tuple, but in unpacking, we extract all those values stored in the tuples into variables.

Example: 1

 Tuple = (“John”, 23567, “Software Engineer”)
(eName, eID, eTitle) = Tuple
print(“Packed tuples is:”, Tuple)
print(“Employee name is:”, eName)
print(“Employee ID is:”, eID)
print(“Employee Title is:”, eTitle)

Output:

Packed tuples is: (“John”, 23567, “Software Engineer”)
Employee name is: John
Employee ID is: 23567
Employee Title is: Software Engineer

If you notice in the above case in line number 2, we are unpacking the tuple into some variables.

Note: The number of items in the tuple should be equal to the number of the variables in the unpacked tuple.

NamedTuple

Python provides a special type of function called namedtuple() that comes from the collection module.

Named Tuples are similar to a dictionary that contains keys and values. But the difference is that in the dictionary we can only access the value using the key but NamedTuple supports access from both the value and the key.

There are three ways through which we can access the values of nemaedtuple().

  • Access by index
  • Access by key
  • Access by getattr() method

Example: 1

 import collections

Employee = collections.namedtuple(‘Employee’, [‘name’, ‘ID’, ‘Title’])
Emp = Employee(‘John’, ‘23567’, ‘Software Engineer’)
#Accessing using index
print(“Employee name is:”, Emp[0])
# Accessing using key
print(“Employee ID is:”, Emp.ID)
#Access by getattr() method
print(“Employee Title is:”, getattr(Emp, ‘Title’))

Output:

Employee name is: John
Employee ID is: 23567
Employee Title is: Software Engineer

We also have Three conversion Operations supported for namedtuples() function.

  • _make()
  • _asdict()
  • **(Double start) operator

Example: 2

 import collections

Employee = collections.namedtuple(‘Employee’, [‘name’, ‘ID’, ‘Title’])
Emp = Employee(‘John’, ‘23567’, ‘Software Engineer’)
Emp1 = [‘Mathew’, ‘45783’, “Software Developer”]
Emp2 = {‘name’ : “Helen”, ‘ID’ : 56873, ‘Title’ : “Test Lead”}

#Using _make()
print(Employee._make(Emp1))

#Using _asdict()
print(Emp._asdict())

#Using ** operator
print(Employee(**Emp2))

Output:

Employee(name=’Mathew’, ID=’45783′, Title=’Software Developer’)
OrderedDict([(‘name’, ‘John’), (‘ID’, ‘23567’), (‘Title’, ‘Software Engineer’)])
Employee(name=’Helen’, ID=56873, Title=’Test Lead’)

Return Tuple

We can return the collection of values or tuples using the return statement.

Example: 1

 
def my_fun():
               name = “John”
               ID = 23567
               Title = “Software Engineer”
               return (name, ID, Title)

employee = my_fun()
print(“Employee detail is:”, employee)

Output:

Employee detail is: (‘John’, 23567, ‘Software Engineer’)

Tuple Index out of range

Index out of range is one of the common exceptions that we will get while working with Tuples or list. This exception usually occurs when you try to access an item outside the tuple, range, which means if the tuples contain only 3 elements, and if you try to access the 4th element then it will get tuple index out of the range exception.

Example: 1

 Tuple = (4, 7, 1.2, “Hi”)
print(Tuple[4])

Output:

Traceback (most recent call last):
File “<pyshell#1>”, line 1, in <module>
Tuple[4]
IndexError: tuple index out of range

If you observe in the above example, we are trying to access the element which is present at the 5th position, but there is no element present there, thus it throws tuple index out of range exception.

Deleting the Tuple

We cannot delete individual elements from the tuple as tuples are immutable. The only way to delete the elements from the tuple is to delete the entire tuple.

Python provides an in-built function ‘del’ to delete the entire tuple.

Example: 1

 Tuple = (2, 4.5, “Python”)
print(“Before deleting the tuple:”, Tuple)
del Tuple
print(“After Deleting the tuple:”, Tuple)

Output:

Before deleting the tuple: (2, 4.5, “Python”)
Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
print(“After Deleting the tuple:”, Tuple)
NameError: name ‘Tuple’ is not defined

In the above example, after deleting the tuple we are trying to print the Tuple, but it doesn’t exist anymore. Hence it throws NameError.

Basic Tuple Operations

Using tuples, we can perform some basic operations like concatenation, repetition, etc.

Let’s see all the basic operations with some examples.

Example: 1 – Tuple Concatenation

We can concatenate the tuples using the ‘+’ operator.

 Tuple1 = (3, 5, “Hi”)
Tuple2 = (5.6, 1, “Python”)
print(“Tuple 1 is:”, Tuple1)
print(“Tuple 2 is”, Tuple2)
print(“Concatenation of Tuple 1 and Tuple 2 is:”, Tuple1+Tuple2)

Output:

Tuple 1 is: (3, 5, “Hi”)
Tuple 2 is: (5.6, 1, “Python”)
Concatenation of Tuple 1 and Tuple 2 is: (3, 5, ‘Hi’, 5.6, 1, ‘Python’)

Example: 2 – Tuple Repetition

Tuple repetition means repeating the elements of the tuples multiple times. This can be achieved using the ‘*’ operator.

Tuple = (3, 1, 5.6, “Python”)
print(“Before the repetition the tuple is:”, Tuple)
print(“After the repetition the tuple is:”, Tuple*3)

Output:

Before the repetition, the tuple is: (3, 1, 5.6, “Python”)
After the repetition, the tuple is: (3, 1, 5.6, “Python”, 3, 1, 5.6, “Python”, 3, 1, 5.6, “Python”)

Example: 3 – Membership Operator

Using the ‘in’ operator, we can check if a particular element is present in the Tuple. It returns the Boolean value True if the element is present in the tuple and returns False if the element is not present.

Tuple = (3, 2, 6)
print(“Is element 2 present in Tuple:”, 2 in Tuple)

Output:

Is element 2 present in Tuple: True

Built-in Tuples Methods

Python provides a couple of built-in methods for tuples as described in the below table.

MethodsDescription
any()Returns True if any element present in a tuple and returns False if the tuple is empty
min()Returns smallest element (Integer) of the Tuple
max()Returns largest element (Integer) of the Tuple
len()Returns the length of the Tuple
sorted()Used to sort all the elements of the Tuple
sum()Returns sum of all elements (Integers) of the Tuples

Let’s see how to use all the methods with an example.

Example: 1 – any() method

Tuple = (3, 1, 4.5)
print(“Is there any elements present in Tuple:”, any(Tuple))
Tuple1 = ()
print(“Is there any elements present in Tuple1:”, any(Tuple1))

Output:

Is there any elements present in Tuple: True
Is there any elements present in Tuple1: False

Example: 2 – min() method

Tuple = (3, 5.6, 5, 8)
print(“Smallest element in the tuples is:”, min(Tuple))

Output:

Smallest element in the tuples is: 3

Example: 3 – max() method

Tuple = (3, 5.6, 5, 8)
print(“Largest element in the tuples is:”, max(Tuple))

Output:

Largest element in the tuples is: 8

Example: 4 – len() method

Tuple = (3, 5.6, 5, 8)
print(“Length of the tuple is:”, len(Tuple))

Output:

Length of the tuple is: 4

Example: 5 – sorted() method

Tuple = (2, 3.5, 1, 6, 4)
print(“Sorted integer is:”, sorted(Tuple))
Tuple1 = (‘e’, ‘a’, ‘u’, ‘o’, ‘i’)
print(“Sorted character is:”, sorted(Tuple1))

Output:

Sorted integer is: (1, 2, 3.5, 4, 6)
Sorted character is: (‘a’, ‘e’, ‘i’, ‘o’, ‘u’)

Example: 6 – sum() method

Num = (3, 5.1, 2, 9, 3.5)
print("Sum of all the numbers in the tuples is:", sum(Num))

Output:

Sum of all the numbers in the tuples is: 22.6

Conclusion

A tuple is one of the data types in Python, which is also referred to as data structure.

A Python Tuple is used to store a large number of values of any data types in one single variable. Tuples are immutable, hence it boosts the performance of accessing the values from the tuple.

When you are working with tuples, then it’s mandatory to remember all the tuple built-in methods.

Hope you would have gained immense knowledge on the concept of Tuple in Python!!

Was this helpful?

Thanks for your feedback!

Leave a Comment