Python Tuples

Tuple is a built-in data structure in Python for storing a collection of objects. A tuple is quite similar to a Python list in terms of indexing, nested objects, and repetition; however, the main difference between both is that the tuples in Python are immutable, unlike the Python list which is mutable.

Let us see a simple example of initializing a tuple in Python.

Example

# creating a tuple  

T = (20, 'Learn Python', 35.75, [20, 40, 60])  

  

print(T)

Output:

(20, 'Learn Python', 35.75, [20, 40, 60])

Explanation:

In the above example, we have created a simple tuple consisting of multiple elements of different data types. Each element in this tuple is indexed, meaning it can be accessed using its position in the list, as shown below:

  • T[0] = 20 (Integer)
  • T[1] = ‘TpointTech’ (String)
  • T[2] = 35.75 (Float)
  • T[3] = [20, 40, 60] (Nested List)

Characteristics of Python Tuples

Tuple in Python is a data structure, which is

  • Ordered: Each data element in a tuple has a particular order that never changes.
  • Immutable: The data elements of tuple cannot be changed once initialized.

Let us take a look at the following example showing that Tuples are immutable.

Example

# creating a tuple    

my_tpl = (25, 16.25, 'Learn Python', [20, 40, 60], 3e8)    

print(my_tpl)  

  

# trying to changing the element of the tuple    

# my_tpl[1] = 'welcome' # raise TypeError

Output:

(25, 16.25, 'Learn Python', [20, 40, 60], 300000000.0)

Creating a Tuple

All the objects-also known as “elements”-must be separated by a comma, enclosed in parenthesis (). Although parentheses are not required, they are recommended.

Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be contained in a tuple.

Let us consider the following example demonstrating the inclusion of different data types in a tuple:

Example

# Python program to show how to create a tuple  

  

# Creating an empty tuple      

empty_tpl = ()      

print("Empty tuple: ", empty_tpl)      

      

# Creating a tuple having integers      

int_tpl = (13, 56, 27, 18, 11, 23)  

print("Tuple with integers: ", int_tpl)      

      

# Creating a tuple having objects of different data types  

mix_tpl = (6, "Tpointtech", 17.43)      

print("Tuple with different data types: ", mix_tpl)      

      

# Creating a nested tuple      

nstd_tpl = ("Tpointtech", {4: 5, 6: 2, 8: 2}, (5, 3, 15, 6))      

print("A nested tuple: ", nstd_tpl)

Output:

Empty tuple: ()
Tuple with integers: (13, 56, 27, 18, 11, 23)
Tuple with different data types: (6, 'Tpointtech', 17.43)
A nested tuple: ('Tpointtech', {4: 5, 6: 2, 8: 2}, (5, 3, 15, 6))

Explanation:

In the above snippet of code, we have created four different tuples containing different types of elements. The first tuple is an empty tuple defined using the parentheses with no element in between. After that, we have defined an integer tuple consisting of 6 integer values between the parentheses separated by the commas. The third tuple is comprised of three objects of different data types – integer, string, and float. At last, we have defined a tuple as a different object, including another tuple.

Accessing Tuple Elements

In Python, we can access any object of a tuple using indices. The objects or elements of a tuple can be accessed by referring to the index number, inside of square brackets ‘[]’.

Let us consider the following example illustrating how to access an element of a tuple using indexing:

Example

# Python program to show how to access tuple elements      

  

# Creating a tuple having six elements  

sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")   

  

# accessing the elements of a tuple using indexing  

print("sampleTuple[0] =", sampleTuple[0])  

print("sampleTuple[1] =", sampleTuple[1])  

print("sampleTuple[-1] =", sampleTuple[-1])   # negative indexing  

print("sampleTuple[-2] =", sampleTuple[-2])

Output:

sampleTuple[0] = Apple
sampleTuple[1] = Mango
sampleTuple[-1] = Berries
sampleTuple[-2] = Guava

Explanation:

In the above example, we have created a tuple consisting of six elements. We have then used the indexing to access the different elements of the tuple.

Slicing in Tuple

Slicing a tuple means dividing a tuple into smaller tuples with the help of indexing. In order to slice a tuple, we need to specify the starting and ending index value, that will return a new tuple with the specified objects.

We can slice a tuple using the colon ‘:’ operator separating the start and end index as shown below:

Syntax:

It has the following syntax:

tuple[start:end]  

Python Tuple Slicing Example

Let us consider a simple example showing the way of slicing a tuple in Python.

Example

# Python program to show how slicing works in Python tuples  

  

# Creating a tuple  

sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")  

  

# Using slicing to access elements of the tuple  

print("Elements between indices 1 and 5: ", sampleTuple[1:5])  

  

# Using negative indexing in slicing  

print("Elements between indices 0 and -3: ", sampleTuple[:-3])  

  

# Printing the entire tuple by using the default start and end values  

print("Entire tuple: ", sampleTuple[:])

Output:

Elements between indices 1 and 5: ('Mango', 'Banana', 'Orange', 'Guava')
Elements between indices 0 and -3: ('Apple', 'Mango', 'Banana')
Entire tuple: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava', 'Berries')

Explanation:

In this example, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have printed the tuple of elements ranging from 1 to 5 using the slicing method. We have then printed the elements ranging from 0 to -3 using the negative indexing in slicing. At last, we have printed the entire tuple using the colon ‘:’ operator only without specifying the start and end index values.

Deleting a Tuple

Unlike lists, tuples are immutable data types meaning that we cannot update the objects of a tuple once it is created. Therefore, removing the elements of the tuple is also not possible. However, we can delete the entire tuple using the ‘del’ keyword as shown below.

Syntax:

It has the following syntax:

del tuple_name  

Python Example to Delete a Tuple

Let us consider the following snippet of code illustrating the method of deleting a tuple with the help of the ‘del’ keyword. Here is a simple example showing the way of deleting a tuple in Python.

Example

# Python program to show how to delete elements of a Python tuple  

  

# Creating a tuple  

sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")  

# printing the entire tuple for reference  

print("Given Tuple:", sampleTuple)  

  

# Deleting a particular element of the tuple using the del keyword  

try:  

    del sampleTuple[3]  

    print(sampleTuple)  

except Exception as e:  

    print(e)  

  

# Deleting the variable from the global space of the program using the del keyword  

del sampleTuple  

  

# Trying accessing the tuple after deleting it  

try:  

    print(sampleTuple)  

except Exception as e:  

    print(e)

Output:

Given Tuple: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava', 'Berries')
'tuple' object doesn't support item deletion
name 'sampleTuple' is not defined

Explanation:

Here, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have then printed the entire tuple for reference. After that, we have used the try and except blocks to delete a particular element from the tuple using the del keyword. As a result, an exception has been raised saying ‘tuple’ object doesn’t support item deletion. We have then used the del keyword to delete the entire tuple and tried printing it. As a result, we can observe another exception saying name ‘sampleTuple’ is not defined.

Changing the Elements in Tuple

Once we create a tuple, it is impossible for us to change its elements due its immutable nature. However, there is a way to update the elements of a tuple. We can convert the tuple into a list, change the list, and convert the list back into a tuple.

Python Example to Change the Element in Tuple

Let us see a simple example showing the way of updating elements of a Tuple in Python.

Example

# Python program to demonstrate the approach of changing the element in the tuple  

  

# creating a tuple  

fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  

  

# printing the tuple before update  

print("Before Changing the Element in Tuple...")  

print("Tuple =", fruits_tuple)  

  

# converting the tuple into the list  

fruits_list = list(fruits_tuple)  

  

# changing the element of the list  

fruits_list[2] = "grapes"  

print("Converting", fruits_tuple[2], "=>", fruits_list[2])  

  

# converting the list back into the tuple  

fruits_tuple = tuple(fruits_list)  

  

# printing the tuple after update  

print("After Changing the Element in Tuple...")  

print("Tuple =", fruits_tuple)

Output:

Before Changing the Element in Tuple...
Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
Converting banana => grapes
After Changing the Element in Tuple...
Tuple = ('mango', 'orange', 'grapes', 'apple', 'papaya')

Explanation:

In this example, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have converted the tuple into a list using the list() method. We have then changed the element at index 2 of the list to ‘grapes’ and used the tuple() method to convert the update list back to the tuple. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element at index 2 also changed from ‘banana’ to ‘grapes’ respectively.

Adding Elements to a Tuple

Since Tuple is an immutable data type, it does not have the built-in append() method to add the elements. However, there are few ways we can use in order to add an element to a tuple.

Converting the Tuple into a List

In order to add a new element to a tuple, we can follow a similar approach we used while changing the element in a tuple. The approach follows the steps discussed below:

Step 1: Convert the Tuple into a List.

Step 2: Add the required element to the list using the append() method.

Step 3: Convert the List back into the Tuple.

Let us consider the following snippet of code, demonstrating the same.

Example

# Python program to demonstrate an approach of adding the element in the tuple by converting it into a list  

  

# creating a tuple  

fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  

  

# printing the tuple before update  

print("Before Adding a New Element in Tuple...")  

print("Original Tuple =", fruits_tuple)  

  

# converting the tuple into the list  

fruits_list = list(fruits_tuple)  

  

# changing the element of the list  

fruits_list.append("blueberry")  

print("Adding New Element -> 'blueberry'")  

  

# converting the list back into the tuple  

fruits_tuple = tuple(fruits_list)  

  

# printing the tuple after update  

print("After Adding a New Element in Tuple...")  

print("Updated Tuple =", fruits_tuple)

Output:

Before Adding a New Element in Tuple...
Original Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
Adding New Element -> 'blueberry'
After Adding a New Element in Tuple...
Updated Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya', 'blueberry')

Explanation:

In the above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have convert the tuple into a list using the list() method. We have then added a new element ‘blueberry’ in the list using the append() method. After that, we have used the tuple() method to convert the update list back to the tuple. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element ‘blueberry’ has been added to the given tuple respectively.

Adding a Tuple to a Tuple

In Python, we are allowed to add multiple tuples to tuples. Therefore, if we want to insert a new element to a tuple, we can follow the steps as shown below:

Step 1: Create a new Tuple with the element(s) we want to add.

Step 2: Adding the new tuple to the existing tuple.

Let us consider the following example, illustrating the same.

Example

# Python program to demonstrate an approach of adding the element in the tuple by adding a new tuple to the existing one  

  

# creating a tuple  

fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  

  

# printing the tuple before update  

print("Before Adding a New Element in Tuple...")  

print("Original Tuple =", fruits_tuple)  

  

# creating a new tuple consisting new element(s)  

temp_tuple = ("pineapple", )  

  

# adding the new tuple to the existing tuple  

# fruits_tuple = fruits_tuple + temp_tuple  

fruits_tuple += temp_tuple  

  

# printing the tuple after update  

print("Adding New Element -> 'pineapple'")  

print("After Adding a New Element in Tuple...")  

print("Updated Tuple =", fruits_tuple)

Output:

Before Adding a New Element in Tuple...
Original Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
Adding New Element -> 'pineapple'
After Adding a New Element in Tuple...
Updated Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya', 'pineapple')

Explanation:

In the above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have created a new tuple consisting of another element ‘blueberry’. After that, we have added the new tuple to the existing tuple using the ‘+’ operator. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element ‘pineapple’ has been added to the given tuple respectively.

Unpacking Tuples

While initializing a tuple, we generally assign objects to it. This process is known as ‘packing’ a tuple. However, Python offers us an accessibility to extract the objects back into variables. This process of extracting the objects from a tuple and assign them to different variables is known as ‘unpacking’ a tuple.

Python Example for Unpacking Tuples

Let us consider the following example illustrating the way of unpacking a tuple in Python.

Example

# Python program to demonstrate an approach of unpacking a tuple  

  

# creating a tuple (Packing a Tuple)  

fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  

  

# printing the given tuple for reference  

print("Given Tuple :", fruits_tuple)  

  

# unpacking a tuple  

(varOne, varTwo, varThree, varFour, varFive) = fruits_tuple  

  

# printing the results  

print("First Variable :", varOne)  

print("Second Variable :", varTwo)  

print("Third Variable :", varThree)  

print("Fourth Variable :", varFour)  

print("Fifth Variable :", varFive)

Output:

Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya')
First Variable : mango
Second Variable : orange
Third Variable : banana
Fourth Variable : apple
Fifth Variable : papaya

Explanation:

In the above snippet of code, we have created a tuple of five elements – mango, orange, banana, apple, and papaya. We have printed the initialized tuple for reference. After that, we have unpacked the tuple by assigning each element of the tuple at right to their corresponding variables at left. At last, we have printed the values of different initialized variables. As a result, the tuple is unpacked successfully, and the values are assigned to the variables.

Note:While unpacking a tuple, the number of variables on left-hand side should be equal to the number of elements in a given tuple. In case, the variables do not match the size of the tuple, we can use an asterisk ‘*’ in order to store the remaining elements as a list.

Looping Tuples

Python offers different ways to loop through a tuple. Some of these ways are as follows:

  • Using ‘for’ loop
  • Using ‘while’ loop

Python Looping Tuples Example

Here is a simple example showing the ways of looping through a Tuple in Python

Example

# Python program to loop through a tuple  

  

# creating a tuple  

fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  

  

# printing the given tuple for reference  

print("Given Tuple :", fruits_tuple)  

  

print("Looping with 'for' Loop:")  

i = 1  

# iterating through the tuple  

for fruit in fruits_tuple:  

    # printing the element  

    print(i, "-", fruit)  

    i += 1  

  

print("\nLooping with 'while' Loop:")  

# initializing an iterable with 0  

j = 0  

# using the while loop to iterate through the tuple  

while j < len(fruits_tuple):  

    # printing the element of the tuple  

    print(j + 1, "-", fruits_tuple[j])  

    # incrementing the index value by 1  

    j += 1

Output:

Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya')
Looping with 'for' Loop:
1 - mango
2 - orange
3 - banana
4 - apple
5 - papaya

Looping with 'while' Loop:
1 - mango
2 - orange
3 - banana
4 - apple
5 - papaya

Explanation:

In this example, we have created a tuple containing some elements and printed it for reference. We have then used the ‘for’ and ‘while’ loop to iterate through each element of tuple and printed them. As a result, the elements of the tuple are printed successfully.

Tuple Operators in Python

The following table displays the list of different operators to work with Python tuples.

S. No.Python OperatorPython ExpressionResultDescription
1+(2, 4, 6) + (3, 5, 7)(2, 4, 6, 3, 5, 7)Concatenation
2*(‘Apple’, ) * 3(‘Apple’,
‘Apple’,
‘Apple’)
Repetition
3in, not in4 in (2, 4, 6, 8, 10)TrueMembership

Python Example for Tuple Operators

Let us now consider the following example illustrating the use of different operators on Tuples in Python.

Example

# Python program to illustrate the use of operators in the case of tuples  

  

# creating a tuple for concatenation  

vegetables_tuple = ('Potato', 'Tomato', 'Onion')  

# printing the tuple  

print("Vegetables Tuple =>", vegetables_tuple)  

  

# creating another tuple for concatenation  

fruits_tuple = ('Mango', 'Apple', 'Orange')  

# printing the tuple  

print("Fruits Tuple =>", fruits_tuple)  

  

# concatenating the tuples using the + operator  

tuple_of_food_items = vegetables_tuple + fruits_tuple  

# printing the resultant tuple  

print("Concatenated Tuple: Tuple of Food Items =>", tuple_of_food_items)  

  

# creating a tuple for repetition  

sampleTuple = ('Mango', 'Grapes', 'Banana')  

  

# printing the original tuple  

print("Original tuple =>", sampleTuple)  

  

# Repeating the tuple elements for 4 times using the * operator  

sampleTuple = sampleTuple * 4  

  

# printing the new tuple  

print("New tuple =>", sampleTuple)  

  

# creating a tuple for membership  

test_tuple = (12, 23, 35, 76, 84)  

# printing the tuple  

print("Given tuple =>", test_tuple)  

  

# test cases  

n = 35  

m = 47  

  

# checking whether variable n and m belongs to the given tuple or not using the membership operator  

if n in test_tuple:  

    print("Yes.", n, "is present in the tuple", test_tuple)  

else:  

    print("No.", n, "is NOT present in the given tuple.")  

  

if m in test_tuple:  

    print("Yes.", m, "is present in the tuple", test_tuple)  

else:  

    print("No.", m, "is NOT present in the given tuple.")

Output:

Vegetables Tuple => ('Potato', 'Tomato', 'Onion')
Fruits Tuple => ('Mango', 'Apple', 'Orange')
Concatenated Tuple: Tuple of Food Items => ('Potato', 'Tomato', 'Onion', 'Mango', 'Apple', 'Orange')
Original tuple => ('Mango', 'Grapes', 'Banana')
New tuple => ('Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana')
Given tuple => (12, 23, 35, 76, 84)
Yes. 35 is present in the tuple (12, 23, 35, 76, 84)
No. 47 is NOT present in the given tuple.

Explanation:

In this example, we have used the concatenation operator ‘+’, to add the elements of two different tuples in a new tuple. We have used the repetition operator ‘*’ to repeat the elements of the tuple for given number of times. We have also used the membership operator ‘in’ to check if the passed item is a member of the tuple.

Tuple Methods in Python

Python tuple, being a collection of immutable items, makes it difficult to alter or modify the initialized objects of the tuple. However, Python offers two built-in methods to work with tuples. These methods are as listed below:

  1. count()
  2. index()

Let us now discuss these methods in detail with the help of some examples.

The count() Method

The count() method is a built-in Python method to count the occurrence of the specified element in a tuple.

Syntax:

It has the following syntax:

tuple_name.count(item)  

Parameter:

  • item (required): The item parameter is the item to be searched in the tuple.

Return:

  • The number of times the specified item appeared in the tuple.

Let us now look at the following example illustrating the use of the count() method in the case of Python tuples.

Example

# Python program to demonstrate the use of count() method in the case of tuples  

  

# creating tuples  

T1 = (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)  

T2 = ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')  

  

# counting the occurrence of 2 in the tuple T1  

resultOne = T1.count(2)  

  

# counting the occurence of 'Mango' in the tuple T2  

resultTwo = T2.count('Mango')  

  

# printing the results  

print("Tuple T1 =>", T1)  

print("Total Occurrence of 2 in T1 =>", resultOne)  

  

# printing the results  

print("\nTuple T2 =>", T2)  

print("Total Occurrence of 'Mango' in T2 =>", resultTwo)

Output:

Tuple T1 => (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)
Total Occurrence of 2 in T1 => 5

Tuple T2 => ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')
Total Occurrence of 'Mango' in T2 => 4

Explanation:

In this example, we have used the count() method to count the occurrence of passed variables in the given tuple.

The index() Method

The index() method is a built-in Python method to search for a specified element in the tuple and return its position.

Syntax:

It has the following syntax:

tuple_name.index(item)  

Parameter:

  • item (required): The item parameter is the item to be searched in the tuple.
  • start (optional): The start parameter indicates the starting index from where the searching is begun.
  • end (optional): The end parameter indicates the ending index till where the searching is done.

Return:

  • An Integer Value indicating the index of the first occurrence of the specified value.

Let us now look at the following example illustrating the use of the index() method in the case of Python tuples.

Example

# Python program to demonstrate the use of index() method in the case of tuples  

  

# creating tuples  

T1 = (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)  

T2 = ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')  

  

# searching for the occurrence of 2 in the tuple T1  

resultOne = T1.index(2)  

resultTwo = T1.index(2, 5)  

  

# searching for the occurence of 'Mango' in the tuple T2  

resultThree = T2.index('Mango')  

resultFour = T2.index('Mango', 3)  

  

# printing the results  

print("Tuple T1 =>", T1)  

print("First Occurrence of 2 in T1 =>", resultOne)  

print("First Occurrence of 2 after 5th index in T1 =>", resultTwo)  

  

# printing the results  

print("\nTuple T2 =>", T2)  

print("First Occurrence of 'Mango' in T2 =>", resultThree)  

print("First Occurrence of 'Mango' after 3rd index in T2 =>", resultFour)

    Output:

    Tuple T1 => (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)
    First Occurrence of 2 in T1 => 1
    First Occurrence of 2 after 5th index in T1 => 5
    
    Tuple T2 => ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')
    First Occurrence of 'Mango' in T2 => 2
    First Occurrence of 'Mango' after 3rd index in T2 => 5
    

    Explanation:

    In this example, we have used the index() method to return the index value of the first occurrence of the passed elements in the given tuple.

    Some Other Methods for Python Tuples

    Apart from the count() and index() methods, we have some other methods to work with tuples in Python. These methods as follows:

    • max()
    • min()
    • len()

    Let us now discuss these methods in detail.

    The max() Method:

    Python’s max() method is used to return the maximum value in the tuple.

    Syntax:

    It has the following syntax:

    max(object)  

    Parameter:

    • object (required): The object parameter can be any iterable such as Tuple, List, etc.

    Return:

    • The largest element from that iterable (Tuple, List, etc.)

    Let us now consider the following example illustrating the use of the max() method to find the largest integer in the given tuple.

    Example

    # Python program to demonstrate the use of max() method in the case of tuples  
    
      
    
    # creating a tuple  
    
    sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)  
    
      
    
    # printing the tuple for reference  
    
    print("Given Tuple =>", sampleTuple)  
    
      
    
    # using the max() method to find the largest element in the tuple  
    
    largest_element = max(sampleTuple)  
    
      
    
    # printing the result for the users  
    
    print("The Largest Element in the Given Tuple =>", largest_element)

      Output:

      Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
      The Largest Element in the Given Tuple => 9
      

      Explanation:

      In the example, we have used the max() method on the given tuple to find the largest element in it.

      The min() Method

      Python provides a method called min() to find the minimum value in the tuple.

      Syntax:

      It has the following syntax:

      min(object)  

      Parameter:

      • object (required): The object parameter can be any iterable such as Tuple, List, etc.

      Return:

      • The smallest element from that iterable (Tuple, List, etc.)

      Let us now consider the following example illustrating the use of the min() method to find the smallest integer in the given tuple.

      Example

      # Python program to demonstrate the use of min() method in the case of tuples  
      
        
      
      # creating a tuple  
      
      sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)  
      
        
      
      # printing the tuple for reference  
      
      print("Given Tuple =>", sampleTuple)  
      
        
      
      # using the min() method to find the smallest element in the tuple  
      
      smallest_element = min(sampleTuple)  
      
        
      
      # printing the result for the users  
      
      print("The Smallest Element in the Given Tuple =>", smallest_element)

        Output:

        Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
        The Smallest Element in the Given Tuple => 0
        

        Explanation:

        In the example, we have used the min() method on the given tuple to find the smallest element in it.

        The len() Method

        Python’s len() method is used to find the length of the given sequence such as Tuple, List, String, etc.

        Syntax:

        It has the following syntax:

        len(object)  

        Parameter:

        • object (required): The object parameter can be any iterable such as Tuple, List, etc.

        Return:

        • The number of elements in that iterable (Tuple, List, etc.)

        Let us now consider the following example illustrating the use of the len() method to find the length of the given tuple.

        Example

        # Python program to demonstrate the use of len() method in the case of tuples  
        
          
        
        # creating a tuple  
        
        sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)  
        
          
        
        # printing the tuple for reference  
        
        print("Given Tuple =>", sampleTuple)  
        
          
        
        # using the len() method to find the length of the tuple  
        
        length_of_tuple = len(sampleTuple)  
        
          
        
        # printing the result for the users  
        
        print("Number of Elements in the Given Tuple =>", length_of_tuple)

          Output:

          Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
          Number of Elements in the Given Tuple => 10
          

          Explanation:

          In the example, we have used the len() method on the given tuple to find the total number of elements present in it.

          Conclusion

          In conclusion, Python tuple is an essential data structure that allows us to store a collection of items in a single variable. Unlike lists, tuples are immutable, meaning their values cannot be changed after creation. They are useful when we want to ensure data remains constant throughout the program. Tuples can store multiple data types, support indexing and slicing, and are more memory-efficient than lists. Understanding how to use tuples helps improve the reliability and performance of our Python code.

          Comments

          Leave a Reply

          Your email address will not be published. Required fields are marked *