What is tuple in Python?

A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change is reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot remove any element but can find in the tuple. We can use indexing to get elements. It also allows traversing elements in reverse order by using negative indexing. Tuple supports various methods like max(), sum(), sorted(), Len() etc.

To create a tuple, we can declare it as below.

Example:

  1. # Declaring tuple  
  2. tup = (2,4,6,8)  
  3. # Displaying value  
  4. print(tup)  
  5.   
  6. # Displaying Single value  
  7. print(tup[2])  

Output:

(2, 4, 6, 8)
6
Python Interview Questions

It is immutable. So updating tuple will lead to an error.

Example:

  1. # Declaring tuple  
  2. tup = (2,4,6,8)  
  3. # Displaying value  
  4. print(tup)  
  5.   
  6. # Displaying Single value  
  7. print(tup[2])  
  8.   
  9. # Updating by assigning new value  
  10. tup[2]=22  
  11. # Displaying Single value  
  12. print(tup[2])  

Output:

tup[2]=22 
TypeError: 'tuple' object does not support item assignment 
(2, 4, 6, 8)
Python Interview Questions