Tuple is a type of variable, In this tutorial you will learn what is tuple function and how to use tuple in python application development.
What is tuple 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.
We can add all different type of values in Tuple in python, here is an example.
tup1 = ('python', 'php', "C#", 2020); print(tup1);
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); print(tup1[1]); #result: 'php'
You can specify range to retrieve elements from Tuple variable.
tup3 = ("python", "php", "c#", "java", "oracle", "sql", "ai") print(tup3[2:5])
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: print(subject)
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 tup1[1]="Asp";
But we can retrieve some part of Tuple variable and then create a new one.
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;
Here are few commonly used tuple functions
tup1 = ('python', 'php', "C#", 2020); print(len(tup1));
tup1 = ('python', 'php', 'C#'); print(max(tup1)); #result: python tup2 = (500, 600, 800); print(min(tup2)); #result: 500
Things to remember: python tuple variable can hold different type of values just like list object, but we cannot change value of tuple element.