Free Web Development Online Tutorials, Learn to Code
How to use tuple in python, Python tuple examples, python tuple methods, python tuple function

Python tuple example

In this article you will learn how to use Tuple in Python application development.

What is Tuples in Python?

Tuple is immutable python objects, that can hold data in sequence just like list object .

There is a small difference between tuples and lists objects, the tuple cannot be changed unlike list object, so anytime you need to change, you will create a new tuple object

How to define Python Tuple

We can add all different type of values in Tuple in python, here is an example.

tup1 = ('python', 'php', "C#", 2020);

Retrieve values from Tuple variable

You can retrieve values from Tuple variable by using the index number, index always starts from zero.

Remember, if you specify any index number out of range, it will throw exception "tuple index out of range"

tup1 = ('python', 'php', "C#", 2020);
#result: 'php'

You can specify range to retrieve elements from Tuple variable.

tup3 = ("python", "php", "c#", "java", "oracle", "sql", "ai")

Loop Through a Tuple

We can iterate through a Tuple variable using for loop, Retrieving value of each element in a Tuple

tup3 = ("python", "php", "c#", "java", "oracle", "sql", "ai")
 for subject in tup3:

Update Tuple variable

As we specified earlier that Tuple is immutable in python, so we cannot update any values in Tuple variable, but we can take some part of Tuple values and create a new Tuple.

We cannot assign new value to tuple element, 'tuple' object does not support item assignment

tup1 = ('python', 'php', "C#", 2020);

#we cannot write 

But we can retrieve some part of Tuple variable and then create a new one.

Delete Tuple variable

We can delete a Tuple variable reference completely, after deleting the reference if we try to use the variable again, it will throw exception.

tup1 = ('python', 'php', "C#", 2020);        
del tup1;        

Built-in Tuple Functions in Python

Here are few commonly used tuple functions

  1. len() : using this built-in function we can find the length of a tuple variable
    tup1 = ('python', 'php', "C#", 2020);        
  2. max() and min() function: helps finding the element with max or min value
    tup1 = ('python', 'php', 'C#');
    #result: python
    tup2 = (500, 600, 800);
    #result: 500
Python tuple functions

Python tuple examples
Python programming examples | Join Python Course