Tuple in python

tuple in python

Tuple in python As you all familiar with the list in any other programming language, similarly we have one more data set, which is a tuple. The tuple is similar to a list where we can store multiple types of values either string, integer, float, or any other. So if we have a list then why do we use a tuple.

How to Create Tuple in python?

 Firstly, the value of tuples cannot change. If we define the value of tuple, then we can modify its value neither in real-time nor on static time. Tuple is used for non-changeable value. For example, suppose you want to make some entries mandatory in your program so none can change its value then define it in a tuple. 

Secondly, the item in the list is defined in square brackets [] but the tuple item is defined in parentheses () and separated by commas.

Example:

tup = (10, 20, 30, 40, 50) 

Empty, Similar, Mixed Tuple:

 Here are some examples of the different items that can be held in the tuple. Tup1 has no value its an empty tuple; tup2 is the collection of integer items; tup3 has mixed values like integer, string, and float.

 # Empty Tuple initialize with tup1
 tup1 = () 
 print(tup1)
 # Output will be 
  ()

 # tup2 has integer items
 tup2 = (21, 1995, 3) 
 print(tup2)
 # Output will be 
 (21, 1995, 03) 


 # tup3 has mixed values

 tup3 = (1, "Python", 1.56) 
 print(tup3)

 # Output will be 
(1, "Python", 1.56) 

Tuple Packing in python

Tuple can also be defined without parenthesis it is called tuple packing.

 # tuple packing 
 tup = 10, 30, "Packing" 
 print(tup)

# Output :
 10, 30, "Packing"

Creating a tuple with one value may give you a different output. For example, creating a tuple with one item and using type method (In Python type is a built-in method, which comes when figuring out the type of the variable used in the runtime) then it gives different types of output. In first without a comma, it gives the item type. With coma and without parenthesis it gives the same output given the type of item that’s a tuple.

 # Creating a tuple T having one element
 T = ("Hi") 
 print(type(T)) 

 # Output 
 <class 'str'> 

 # With comma 
 T = ("Hi",) 
 print(type(T))

 # Output 
<class 'tuple'>


 # Without parentheses gave the same result which get with comma 
 T = "Hi",
 print(type(T)) 

 # Output 
 <class 'tuple'>

 Nested Tuple in python

 A tuple can also be a collection of tuples, lists, and string.

Example:

# Nested tuple
n_tup = ("Packing", "Making", ( 1, 2, 3, 4 ), [ 10, 20, 30, 40 ] ) 
print( type (n_tup) ) 
print(n_tup) 

# Output : 
<class 'tuple'>

# Output :
 ("Packing", "Making", ( 1, 2, 3, 4 ), [ 10, 20, 30, 40 ] ) 

Access Values in Tuple

Accessing values in tuple there are different ways to access elements in a tuple:

1.By Index

Indexing in the tuple is similar than the list we use index operator [] for accessing any item in tuple. The index starts at 0.  

If you have tup = (10, 20, 30, 40,) then indexing is:

 tup[0] = 10, tup[1] = 20, tup[2] = 30, tup[3] = 40.

 If you use tup[4] = 40, then python will give you IndexError: tuple index out of range. 

Indices must be in integer not in a string or in a float.

 If you use tup[3.1] then it will give you TypeError: tuple indices must be integers, not float. 

Similarly, for accessing values in nested tuple tup[0][3], we have to use to indices first for the desired item in nested tuple, second indices for access the value from the desired item. Please have a look at an example to understand more clearly.

# Indices of tuple

tup1 = ('p', 'a', 'c', 'k', 'k', 'k', 'i', 'n', 'g')

print(tup1[0])

 # Output:
 p 

print(tup1[4]) 

# Output: 
k 
print (tup1[10]) 
# IndexError: tuple index out of range

# Nested tuple
 n_tup = ("python", [ 1, 2, 3, 4 ], ( 5, 6, 7,8 ) ) 
print (n_tup[0][3]) 

# Output: 
h 
print (n_tup[2][3])

# Output:
 8 

2.By Negative Indices:

In Python we can also access the values by negative indexing. The last value referred to  -1, then second last -2 and so on. Below is the example of using indices for both –ve and +ve.

  -6 -5 -4 -3 -2 -1
   P  Y  T  H  O  N 
   0  1  2  3  4  5 
# Negative Indices of tuple 
tup1 = ('p', 'a', 'c', 'k', 'k', 'k', 'i', 'n', 'g') 
print(tup1[-1])

# Output: 
g 
print(tup1[-4])
 
# Output:
k 

3.Tuple Slicing in python:

 We can access the range of the elements within the tuple. The operator “:” colon used for slicing the range of elements in the tuple.

 # Slicing of tuple
 tup1 = ('p', 'a', 'c', 'k', 'k', 'k', 'i', 'n', 'g') 

 # accessing element from 2nd to 5th 
 print(tup1[1:4]) 

 # Output: 
('a', 'c', 'k') 

 # accessing form the beginning to 6th 
 print(tup1[:-4])

 # Output: 
('p', 'a', 'c', 'k', 'k') 

 # accessing from 4th to end 
 print(tup1[4:]) 

 # Output:
 ('k', 'k', 'i', 'n', 'g')

 # accessing from beginning to end 
 print(tup1[:]) 

 #Output: 
('p', 'a', 'c', 'k', 'k', 'k', 'i', 'n', 'g') 

 #print (tup1[10])
 #IndexError: tuple index out of range

Updating a Tuple in Tuple

As we discussed before, the tuple cannot change once it got assigned. But, a nested tuple can change its value if and only if it contains changeable items like a list. For example, whenever we change the value of my_tup it throws an error TypeError: ‘tuple’ object does not support item assignment. But if we change any value of list defined in nested tuple then it gets changed.

 # Updating items in tuple 
 my_tup = (1, 2, 3, 4, 5, 6, [7, 8, 9] ) 

 # Replacing an item from tuple 
 my_tup[1]= 10 #TypeError: 'tuple' object does not support item assignment

 #However the my_tuple contains list. So we can change an item from list
 my_tup[6][0] = 0
 print(my_tup)

 #Output: 
(1, 2, 3, 4, 5, 6, [0, 8, 9]) 

Deleting Tuple in Python

As in the previous topic, we concluded that tuple values cannot be changed. So we cannot delete the items of tuple too. But we can delete a tuple completely.

 del keyword is used for deleting the tuple.

# Deleting items in tuple 
my_tup = (1, 2, 3, 4, 5, 6, [7, 8, 9] )

# Deleting an item from tuple
 del my_tup[1] #TypeError: 'tuple' object doesn't support item deletion 


#However we can delete a whole tuple  
del my_tup 
print(my_tup) #NameError: name 'my_tup' is not defined


 #Because the my_tup doesn't exist after deletion. 

Type of Operator

 ‘+’ – is a concatenate operator. Used to combine the two tuples. 

*’ – is a repeat operator. Used to repeat a specific value a specific number of times.

 # Concatenate
 tup1 = (1, 2, 3, 4, 5,) 
 tup2 = 6, 7, 8, 9, 10
 tup3 = tup1 + tup2 print (tup3) 

# Output :
 (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 

#Repeat 
print (tup1 * 3) 

# Output : 
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5) 

Types of Methods in Tuple

Tuple doesn’t support the addition and deletion of items. So we have only two methods.

MethodsDescription
count(x)it gives the number of x items present in tuple
index(x)it gives the index of first x item present in tuple
len(tuple)it gives the length of a tuple
my_tup = ('p', 'a', 'c', 'k', 'k', 'k', 'i', 'n', 'g')

 #Using count method to find out number of k
 print(my_tup.count('k'))

 # Output: 
 3 

 #Using index method to find out index of first a 
print(my_tup.index('a'))

 # Output: 
 1 

#Using len method to find out length of tuple 
print(len(tup)) 

# Output:
 9 

Types of Operation in Tuple

To find out whether the item exists in a tuple or not, then use keywords either in or not in. The result always comes in true or false.

my_tup = ('p', 'a', 'c', 'k', 'k', 'k', 'i', 'n', 'g')

# Using in operator
 print('a' in my_tup) 

# Output: 
True 
print('s' in my_tup) 

# Output: 
False 

# Using not in operator 
print('c'in my_tup) 

# Output: 
True 

To iterate through each item in a tuple, use a for loop:

Mytup= (“packing”, “unboxing”, “cherry”) 
for x in Mytup: 
print x 

#Output 
packing 
unboxing 
cherry 

Advantages of Tuple

  1. The tuple contains all the mixed values as we studied in our whole article, but the list cannot hold the different data types. 
  2. Tuple values are non-changeable. Iteration through tuple is fast and boosts performance in spite of the list. The values of the tuple are fixed so it can be used as a key for a variable.
  3. The data in the tuple is protected due to its unchangeable property.