A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable.
Just like strings and lists, values in the tuples can also be accessed by their index values,which are integers starting from 0.
The main difference between lists and tuples is that in case of list, a value in the list can be replaced with another value anytime after its creation. Whereas in tuples, the values in tuples an not be replaced with another value, once tuples are created.
Lists allows us to add new item to it. But tuples does not allow us to add new items, once it is created.
fruits = ( 'Mango' , ' Apple ' , 'Banana')
1. Creating Tuples
A tuple is an inbuilt data type in python. In order to create a tuple, the elements of the tuples are enclosed in parenthesis instead of square brackets. All elements of a tuple are separated by commas. The parenthesis, at the time of creation is not necessary, but it is a good practice to use parenthesis. Tuples can have any number of different data items ( i.e. integer, float,string, list etc).
Example 1: A tuple with integer data item
tuple=(10, 20, 30, 40)
print(tuple)
#Output
(10, 20, 30, 40)
Example 2: A tuple with items of different data typles.
tuple = ( 10, 20, "Python" , 10.5, " Program")
print(tuple)
#Output
( 10, 20, "Python" , 10.5, " Program")
Example 3: Nested Tuple.
tuple = ("Python" , [10, 20, 30], ["Program" , 10.5] )
print(tuple)
#Output
("Python" , [10, 20, 30], ["Program" , 10.5] )
Example 4: Tuple can also be created without parenthesis.
tuple = 10, "Python", 10.5
print(tuple)
#Output
( 10, "Python", 10.5 )
Note that, creating a tuple with one element is somewhat different. When we are creating a tuple with one element, we need to add a final comma after the item or element in order to complete the assignment of the tuple
tuple = ( " Python ")
type(tuple)
#Output
<type ' str '>
In the above assignment statement, we are trying to create a tuple with only one item, but when we print its type in python interpreter, the type is not a tuple but it is str.
Thus, create tuple with single element in following way
# With Parenthesis
tuple = ( " Python " , )
type(tuple)
#Output
<type 'tuple' >
# With Parenthesis
tuple = " Python " ,
type(tuple)
#Output
<type 'tuple' >
Accepting Elements from User and Displaying it.
tuple=()
n=int(input("Enter Tuple Size: "))
for i in range(n):
x=int(input())
tuple=tuple+(x,)
print(tuple)
#Output
Enter Tuple Size: 4
10
20
30
40
(10, 20, 30, 40)
2. Accessing Values in Tuples
In order to access the values in a tuple, it is necessary to use the index number enclosed in a square brackets along with the name of the tuple. Accessing the elements from tuples are simillar to accessing the elements in lists.
Example-1: Using square bracket
tuple=(10,20,30,40,50)
print(tuple[1])
print(tuple[3])
print(tuple[4])
#Output
20
40
50
Example-2: Using Slicing
tuple=(10,20,30,40,50)
print(tuple[1:4])
print(tuple[:4])
print(tuple[2:])
print(tuple[:])
print(tuple[::-1])
#Output
(20, 30, 40)
(10, 20, 30, 40)
(30, 40, 50)
(10, 20, 30, 40, 50)
(50, 40, 30, 20, 10)
As with the lists and strings, we can access the elements of the tuple. HOwever, unlike strings and lists, we can not update the values of the tuple i.e. tuples are immutable.
3. Tuples are Immutable
Tuples are immutable. The values or items in the tuple cannot be changed once it is declared. If ypu want to change the value, we have to create new tuple.
tuple=(10,20,30,40,50)
tuple[3]=60
#Output
TypeError: 'tuple' object does not support item assignment
4. Tuple Assignment
Tuple is very attaractive and powerful feature in the python. It allows the assignment of values to a tuple of variables on the left side of the assignment from the tuple of values on the right side of the assignmets.
The number of variables in the tuple on the left side of the assignment must match the number of the elements or items in the tuple on the right of the assignment.
rituja=(1841010,"Rituja","Waghmode","Jalgaon")
vihaan=(1841020,"Vihaan","Gadade","Pune")
(prn,name,surname,address)=rituja
print(prn)
print(address)
(prn,name,surname,address)=vihaan
print(prn)
print(address)
#Output
1841010
Jalgaon
1841020
Pune
Here we have created a tuple name rituja and vihaan with four elements inside it. Now in the next statement, the value of each element of this tuple is assigned to the respective variable. It can be seen that the number of variables to the left of the assignment is four and the number of items in the tuple is also four; hence, the number of values are matching and the assignment is successful.
In the assignment statement, each variable is assigned with a valuethat was inside the tuple and can be asscessed individually. If we had used the traditional assignment procedure, it would have been done in four line of statements. With the help of tuple assignment, it is done in one line statement.
Swapping of two Number using Tuple:
Sometimes we need to swap the value of two variables in the program. With the traditional method, this can be done by using temporary variable for swapping of two variables.
But if we use tuple approach, there is no need to use any temporary variable to swap two values of two variables. All it takes in one statement.
a. With Traditional Approach
a=10
b=20
print("Before Swapping : ",a,b)
temp=a
a=b
b=temp
print("After Swapping : ",a,b)
#Output
Before Swapping : 10 20
After Swapping : 20 10
b. With Tuple
a=10
b=20
print("Before Swapping : ",a,b)
(a,b)=(b,a)
print("After Swapping : ",a,b)
#Output
Before Swapping : 10 20
After Swapping : 20 10
Note: The number if variables on the left side of the assignment must match the number of values on the right side of the assignment.
5. Tuples as Return Value
Tuples can also be returned by the function as a return values. Generally, the function returns only one value but by returning tuple, a function can return more than one values.
Example: suppose, if we want to compute a division with two integers and want to know the quotient and the remainder, both the quotient and remainder can be computed at the same time. two values will be returned, i.e. quotient and remainder, by using the tuple as the return value of the function.
def div_mod(a,b):
quotient=a/b
remainder=a%b
return quotient,remainder
t=div_mod(10,3)
print(t)
print(type(t))
#Output
(3.3333333333333335, 1)
<class 'tuple'>
Here when we tried to see the type of the variable t, it is <class 'tuple'>
We can also use the tuple assignment approach in order to print the quotient and remainder separately.
def div_mod(a,b):
quotient=a/b
remainder=a%b
return quotient,remainder
quot,rem=div_mod(10,3)
print(quot)
print(rem)
print(type(quot))
print(type(rem))
#Output
3.3333333333333335
1
<class 'float'>
<class 'int'>
Here, we have taken two variables at the left side which are quot and rem. Now, when the function div_mod returns the values of quotient and remainder, the values will be stored in quot and rem respectively. Here the type of both variable would e float and int
6. Variable-length Argument Tuples
Variable number of arguments can also be passed to a function. A variable name that is preceded by an asterisk ( * ) collects the arguments into a tuple.
def traverse(*t):
for i in range(len(t)):
print(t[i])
traverse(10,20,30,40,50)
#Output
10
20
30
40
50
Example-01:
Consider the tuple (1,3,5,7,9,2,4,6,8,10). Write a program to print half its values in 1 line and the other half in the next line.
t=(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
print(t[:5])
print(t[5:])
#Output
(1, 3, 5, 7, 9)
(2, 4, 6, 8, 10)
Example-02:
Consider the tuple (12,7,38,56,78). Write a program to print another tuple whose values are even number in the given tuple.
t=(12, 7, 38, 56, 78)
even_list=list()
for i in t:
if(i%2==0):
even_list.append(i)
print(even_list)
#Output
[12, 38, 56, 78]
Example-03: Write a program to create a function create_tup() which accepts a variable number of arguments and print all of them.
def create_tup(*args):
print(args)
>>> create_tup(1,2,3,4,5,6)
(1, 2, 3, 4, 5, 6) #Output
>>> create_tup(10,20,30)
(10, 20, 30) #Output
>>>
In the above example-03, create_tup(1,2,3,4,5,6) called through Python intrepreter with variable number of arguments.