Category: Tuples

  • Tuple Exercises

    Python Tuple Exercise 1

    Python program to find unique numbers in a given tuple −

    T1 =(1,9,1,6,3,4,5,1,1,2,5,6,7,8,9,2)
    T2 =()for x in T1:if x notin T2:
    
      T2+=(x,)print("original tuple:", T1)print("Unique numbers:", T2)</pre>

    It will produce the following output −

    original tuple: (1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2)
    Unique numbers: (1, 9, 6, 3, 4, 5, 2, 7, 8)
    

    Python Tuple Exercise 2

    Python program to find sum of all numbers in a tuple −

    T1 =(1,9,1,6,3,4)
    ttl =0for x in T1:
       ttl+=x
       
    print("Sum of all numbers Using loop:", ttl)
    
    ttl =sum(T1)print("Sum of all numbers sum() function:", ttl)

    It will produce the following output −

    Sum of all numbers Using loop: 24
    Sum of all numbers sum() function: 24
    

    Python Tuple Exercise 3

    Python program to create a tuple of 5 random integers −

    import random
    t1 =()for i inrange(5):
       x = random.randint(0,100)
       t1+=(x,)print(t1)

    It will produce the following output −

    (64, 21, 68, 6, 12)
    
  •  Tuple Methods

    Tuple is one of the fundamental data structures in Python, and it is an immutable sequences. Unlike lists, tuples cannot be modified after creation, making them ideal for representing fixed collections of data. This immutability play a crucial role in various scenarios where data stability and security are important. It can contain elements of different data types, such as integers, floats, strings, or even other tuples.

    Python Tuple Methods

    The tuple class provides few methods to analyze the data or elements. These methods allows users to retrieve information about the occurrences of specific items within a tuple and their respective indices. Since it is immutable, this class doesn’t define methods for adding or removing items. It defines only two methods and these methods provide a convenient way to analyze tuple data.

    Listing All the Tuple Methods

    To explore all available methods for tuples, you can utilize the Python dir() function, which lists all properties and functions related to a class. Additionally, the help() function provides detailed documentation for each method. Here’s an exampl:

    print(dir((1,2)))print(help((1,2).index))

    The above code snippet provides a complete list of properties and functions related to the tuple class. It also demonstrates how to access detailed documentation for a specific method in your Python environment. Here is the output −

    ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
    Help on built-in function index:
    
    index(value, start=0, stop=9223372036854775807, /) method of builtins.tuple inst ance
    
    Return first index of value.
    
    Raises ValueError if the value is not present.
    (END)

    Below are the built-in methods for tuples. Let’s explore each method’s basic functionality −

    Sr.NoMethods & Description
    1tuple.count(obj)Returns count of how many times obj occurs in tuple
    2tuple.index(obj)Returns the lowest index in tuple that obj appears

    Finding the Index of a Tuple Item

    The index() method of tuple class returns the index of first occurrence of the given item.

    Syntax

    tuple.index(obj)
    

    Return value

    The index() method returns an integer, representing the index of the first occurrence of “obj”.

    Example

    Take a look at the following example −

    Open Compiler

    tup1 =(25,12,10,-21,10,100)print("Tup1:", tup1)
    x = tup1.index(10)print("First index of 10:", x)

    It will produce the following output −

    Tup1: (25, 12, 10, -21, 10, 100)
    First index of 10: 2
    

    Counting Tuple Items

    The count() method in tuple class returns the number of times a given object occurs in the tuple.

    Syntax

    tuple.count(obj)
    

    Return Value

    Number of occurrence of the object. The count() method returns an integer.

    Example

    tup1 =(10,20,45,10,30,10,55)print("Tup1:", tup1)
    c = tup1.count(10)print("count of 10:", c)

    It will produce the following output −

    Tup1: (10, 20, 45, 10, 30, 10, 55)
    count of 10: 3
    

    Example

    Even if the items in the tuple contain expressions, they will be evaluated to obtain the count.

    tup1 =(10,20/80,0.25,10/40,30,10,55)print("Tup1:", tup1)
    c = tup1.count(0.25)print("count of 10:", c)

    It will produce the following output −

    Tup1: (10, 0.25, 0.25, 0.25, 30, 10, 55)
    count of 10: 3
  • Join Tuples

    Joining Tuples in Python

    Joining tuples in Python refers to combining the elements of multiple tuples into a single tuple. This can be achieved using various methods, such as concatenation, list comprehension, or using built-in functions like extend() or sum().

    Joining tuples does not modify the original tuples but creates a new tuple containing the combined elements.

    Joining Tuples Using Concatenation (“+”) Operator

    The concatenation operator in Python, denoted by +, is used to join two sequences, such as strings, lists, or tuples, into a single sequence. When applied to tuples, the concatenation operator joins the elements of the two (or more) tuples to create a new tuple containing all the elements from both tuples.

    We can join tuples using the concatenation operator by simply using the + symbol to concatenate them.

    Example

    In the following example, we are concatenating the elements of two tuples “T1” and “T2”, creating a new tuple “joined_tuple” containing all the elements from both tuples −

    # Two tuples to be joined
    T1 =(10,20,30,40)
    T2 =('one','two','three','four')# Joining the tuples
    joined_tuple = T1 + T2
    
    # Printing the joined tupleprint("Joined Tuple:", joined_tuple)

    Following is the output of the above code −

    Joined Tuple: (10, 20, 30, 40, 'one', 'two', 'three', 'four')
    

    Joining Tuples Using List Comprehension

    List comprehension is a concise way to create lists in Python. It is used to generate new lists by applying an expression to each item in an existing iterable, such as a list, tuple, or range. The syntax for list comprehension is −

    new_list =[expression for item in iterable]

    This creates a new list where expression is evaluated for each item in the iterable.

    We can join a tuple using list comprehension by iterating over multiple tuples and appending their elements to a new tuple.

    Example

    In this example, we are joining two tuples, T1 and T2, into a single tuple using list comprehension. The resulting tuple, joined_tuple, contains all elements from both T1 and T2 −

    # Two tuples to be joined
    T1 =(36,24,3)
    T2 =(84,5,81)# Joining the tuples using list comprehension
    joined_tuple =[item for subtuple in[T1, T2]for item in subtuple]# Printing the joined tupleprint("Joined Tuple:", joined_tuple)

    Output of the above code is as follows −

    Joined Tuple: [36, 24, 3, 84, 5, 81]
    

    Joining Tuples Using extend() Function

    The Python extend() function is used to append elements from an iterable (such as another list) to the end of the list. This function modifies the original list in place, adding the elements of the iterable to the end of the list.

    The extend() function is not used for joining tuples in Python. It is used to extend a list by appending elements from another iterable (such as another list), effectively merging the two lists together.

    We can join tuples using the extend() function by temporarily converting the tuples into lists, performing the joining operation as if they were lists, and then converting the resulting list back into a tuple.

    Example

    In the following example, we are extending the first tuple “T1” by converting it into a list “L1”, then adding elements from the second tuple “T2” by first converting it into a list “L2”, and finally converting the merged list back into a tuple, effectively joining the two tuples −

    T1 =(10,20,30,40)
    T2 =('one','two','three','four')
    L1 =list(T1)
    L2 =list(T2)
    L1.extend(L2)
    T1 =tuple(L1)print("Joined Tuple:", T1)

    The output obtained is as shown below −

    Joined Tuple: (10, 20, 30, 40, 'one', 'two', 'three', 'four')
    

    Join Tuples using sum() Function

    In Python, the sum() function is used to add up all the elements in an iterable, such as a list, tuple, or set. It takes an iterable as its argument and returns the sum of all the elements in that iterable.

    We can join a tuple using the sum() function by providing the tuple as an argument to the sum() function. However, since the sum() function is specifically designed for numeric data types, this method only works for tuples containing numeric elements. It will add up all the numeric elements in the tuple and return their sum.

    Syntax

    Following is the syntax for using the sum() function to join tuples in Python −

    result_tuple =sum((tuple1, tuple2),())

    Here, the first argument is a tuple containing the tuples to be joined. The second argument is the starting value for the sum. Since we are joining tuples, we use an empty tuple () as the starting value.

    Example

    In this example, the elements of the first tuple are first appended to an empty tuple. Then elements from the second tuple are appended, resulting in a new tuple that is a concatenation of the two −

    T1 =(10,20,30,40)
    T2 =('one','two','three','four')
    T3 =sum((T1, T2),())print("Joined Tuple:", T3)

    After executing the above code, we get the following output −

    Joined Tuple: (10, 20, 30, 40, 'one', 'two', 'three', 'four')
    

    Joining Tuples using for Loop

    for loop in Python is used for iterating over a sequence (such as a list, tuple, string, or range) and executing a block of code for each element in the sequence. The loop continues until all elements have been processed.

    We can join a tuple using a for loop by iterating over the elements of one tuple and appending each element to another tuple with the “+=” operator.

    Example

    In the following example, we are iterating over each element in tuple T2, and for each element, we are appending it to tuple T1, effectively joining the two tuples −

    T1 =(10,20,30,40)
    T2 =('one','two','three','four')for t in T2:
       T1+=(t,)print(T1)

    We get the output as shown below −

    (10, 20, 30, 40, 'one', 'two', 'three', 'four')
  •  Loop Tuples

    Loop Through Tuple Items

    Looping through tuple items in Python refers to iterating over each element in a tuple sequentially.

    In Python we can loop through the items of a tuple in various ways, with the most common being the for loop. We can also use the while loop to iterate through tuple items, although it requires additional handling of the loop control variable explicitly i.e. an index.

    Loop Through Tuple Items with For Loop

    A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence.

    In a for loop, you can access each item in a sequence using a variable, allowing you to perform operations or logic based on that item’s value. We can loop through tuple items using for loop by iterating over each item in the tuple.

    Syntax

    Following is the basic syntax to loop through items in a tuple using a for loop in Python −

    for item intuple:# Code block to execute

    Example

    In the following example, we are using a for loop to iterate through each element in the tuple “tup” and retrieving each element followed by a space on the same line −

    tup =(25,12,10,-21,10,100)for num in tup:print(num, end =' ')

    Output

    Following is the output of the above code −

    25 12 10 -21 10 100 
    

    Loop Through Tuple Items with While Loop

    A while loop in Python is used to repeatedly execute a block of code as long as a specified condition evaluates to “True”.

    We can loop through tuple items using while loop by initializing an index variable, then iterating through the tuple using the index variable and incrementing it until reaching the end of the tuple.

    An index variable is used within a loop to keep track of the current position or index in a sequence, such as a tuple or array. It is generally initialized before the loop and updated within the loop to iterate over the sequence.

    Syntax

    Following is the basic syntax for looping through items in a tuple using a while loop in Python −

    while condition:# Code block to execute

    Example

    In the below example, we iterate through each item in the tuple “my_tup” using a while loop. We use an index variable “index” to access each item sequentially, incrementing it after each iteration to move to the next item −

    my_tup =(1,2,3,4,5)
    index =0while index <len(my_tup):print(my_tup[index])
       index +=1

    Output

    Output of the above code is as follows −

    1
    2
    3
    4
    5
    

    Loop Through Tuple Items with Index

    An index is a numeric value representing the position of an element within a sequence, such as a tuple, starting from 0 for the first element.

    We can loop through tuple items using index by iterating over a range of indices corresponding to the length of the tuple and accessing each element using the index within the loop.

    Example

    This example initializes a tuple “tup” with integers and creates a range of indices corresponding to the length of the tuple. Then, it iterates over each index in the range and prints the value at that index in the tuple “tup” −

    tup =(25,12,10,-21,10,100)
    indices =range(len(tup))for i in indices:print("tup[{}]: ".format(i), tup[i])

    Output

    We get the output as shown below −

    tup[0]: 25
    tup[1]: 12
    tup[2]: 10
    tup[3]: -21
    tup[4]: 10
    tup[5]: 100
  • Unpack Tuple Items

    Unpack Tuple Items

    The term “unpacking” refers to the process of parsing tuple items in individual variables. In Python, the parentheses are the default delimiters for a literal representation of sequence object.

    Following statements to declare a tuple are identical.

    >>> t1 =(x,y)>>> t1 = x,y
    >>>type(t1)<class'tuple'>

    Example

    To store tuple items in individual variables, use multiple variables on the left of assignment operator, as shown in the following example −

    tup1 =(10,20,30)
    x, y, z = tup1
    print("x: ", x,"y: ","z: ",z)

    It will produce the following output −

    x: 10 y: 20 z: 30
    

    That’s how the tuple is unpacked in individual variables.

    In the above example, the number of variables on the left of assignment operator is equal to the items in the tuple. What if the number is not equal to the items?

    ValueError While Unpacking a Tuple

    If the number of variables is more or less than the length of tuple, Python raises a ValueError.

    Example

    tup1 =(10,20,30)
    x, y = tup1
    x, y, p, q = tup1
    

    It will produce the following output −

      x, y = tup1
      ^^^^
    ValueError: too many values to unpack (expected 2)
      x, y, p, q = tup1
      ^^^^^^^^^^
    ValueError: not enough values to unpack (expected 4, got 3)
    

    Unpack Tuple Items Using Asterisk (*)

    In such a case, the “*” symbol is used for unpacking. Prefix “*” to “y”, as shown below −

    Example 1

    tup1 =(10,20,30)
    x,*y = tup1
    print("x: ","y: ", y)

    It will produce the following output −

    x: y: [20, 30]
    

    The first value in tuple is assigned to “x”, and rest of items to “y” which becomes a list.

    Example 2

    In this example, the tuple contains 6 values and variables to be unpacked are 3. We prefix “*” to the second variable.

    tup1 =(10,20,30,40,50,60)
    x,*y, z = tup1
    print("x: ",x,"y: ", y,"z: ", z)

    It will produce the following output −

    x: 10 y: [20, 30, 40, 50] z: 60
    

    Here, values are unpacked in “x” and “z” first, and then the rest of values are assigned to “y” as a list.

    Example 3

    What if we add “*” to the first variable?

    tup1 =(10,20,30,40,50,60)*x, y, z = tup1
    print("x: ",x,"y: ", y,"z: ", z)

    It will produce the following output −

    x: [10, 20, 30, 40] y: 50 z: 60
    

    Here again, the tuple is unpacked in such a way that individual variables take up the value first, leaving the remaining values to the list “x”.

  •  Update Tuples

    Updating Tuples in Python

    In Python, tuple is an immutable sequence, meaning once a tuple is created, its elements cannot be changed, added, or removed.

    To update a tuple in Python, you can combine various operations to create a new tuple. For instance, you can concatenate tuples, slice them, or use tuple unpacking to achieve the desired result. This often involves converting the tuple to a list, making the necessary modifications, and then converting it back to a tuple.

    Updating Tuples Using Concatenation Operator

    The concatenation operator in Python, denoted by +, is used to join two sequences, such as strings, lists, or tuples, into a single sequence. When applied to tuples, the concatenation operator joins the elements of the two (or more) tuples to create a new tuple containing all the elements from both tuples.

    We can update a tuple using the concatenation operator by creating a new tuple that combines the original tuple with additional elements.

    Since tuples are immutable, updating tuples using concatenation operator does not modify the original tuple but instead creates a new one with the desired elements.

    Example

    In the following example, we create a new tuple by concatenating “T1” with “T2” using the “+” operator −

    # Original tuple
    T1 =(10,20,30,40)# Tuple to be concatenated
    T2 =('one','two','three','four')# Updating the tuple using the concatenation operator
    T1 = T1 + T2
    print(T1)

    It will produce the following output −

    (10, 20, 30, 40, 'one', 'two', 'three', 'four')
    

    Updating Tuples Using Slicing

    Slicing in Python is used to extract a portion of a sequence (such as a list, tuple, or string) by specifying a range of indices. The syntax for slicing is as follows −

    sequence[start:stop:step]

    Where,

    • start is the index at which the slice begins (inclusive).
    • stop is the index at which the slice ends (exclusive).
    • step is the interval between elements in the slice (optional).

    We can update a tuple using slicing by creating a new tuple that includes slices of the original tuple combined with new elements.

    Example

    In this example, we are updating a tuple by slicing it into two parts and inserting new elements between the slices −

    # Original tuple
    T1 =(37,14,95,40)# Elements to be added
    new_elements =('green','blue','red','pink')# Extracting slices of the original tuple# Elements before index 2
    part1 = T1[:2]# Elements from index 2 onward
    part2 = T1[2:]# Create a new tuple 
    updated_tuple = part1 + new_elements + part2
    # Printing the updated tupleprint("Original Tuple:", T1)print("Updated Tuple:", updated_tuple)

    Following is the output of the above code −

    Original Tuple: (37, 14, 95, 40)
    Updated Tuple: (37, 14, 'green', 'blue', 'red', 'pink', 95, 40)
    

    Updating Tuples Using List Comprehension

    List comprehension in Python is a concise way to create lists. It allows you to generate new lists by applying an expression to each item in an existing iterable, such as a list, tuple, or string, optionally including a condition to filter elements.

    Since tuples are immutable, updating a tuple involves converting it to a list, making the desired changes using list comprehension, and then converting it back to a tuple.

    Example

    In the example below, we are updating a tuple by first converting it to a list and using list comprehension to add 100 to each element. We then convert the list back to a tuple to get the updated tuple −

    # Original tuple
    T1 =(10,20,30,40)# Converting the tuple to a list
    list_T1 =list(T1)# Using list comprehension 
    updated_list =[item +100for item in list_T1]# Converting the updated list back to a tuple
    updated_tuple =tuple(updated_list)# Printing the updated tupleprint("Original Tuple:", T1)print("Updated Tuple:", updated_tuple)

    Output of the above code is as follows −

    Original Tuple: (10, 20, 30, 40)
    Updated Tuple: (110, 120, 130, 140)
    

    Updating Tuples Using append() function

    The append() function is used to add a single element to the end of a list. However, since tuples are immutable, the append() function cannot be directly used to update a tuple.

    To update a tuple using the append() function, we need to first convert the tuple to a list, then use append() to add elements, and finally convert the list back to a tuple.

    Example

    In the following example, we first convert the original tuple “T1” to a list “list_T1”. We then use a loop to iterate over the new elements and append each one to the list using the append() function. Finally, we convert the updated list back to a tuple to get the updated tuple −

    # Original tuple
    T1 =(10,20,30,40)# Convert tuple to list
    list_T1 =list(T1)# Elements to be added
    new_elements =[50,60,70]# Updating the list using append()for element in new_elements:
    
    list_T1.append(element)# Converting list back to tuple
    updated_tuple =tuple(list_T1)# Printing the updated tupleprint("Original Tuple:", T1)print("Updated Tuple:", updated_tuple)

    We get the output as shown below −

    Original Tuple: (10, 20, 30, 40)
    Updated Tuple: (10, 20, 30, 40, 50, 60, 70)
  • Access Tuple Items

    Access Tuple Items

    The most common way to access values within a Python tuple is using indexing, We just need to specify the index of the elements we want to retrieve to the square bracket [] notation.

    In Python, a tuple is an immutable ordered collection of elements. “Immutable” means that once a tuple is created, we cannot modify or change its contents. We can use tuples to group together related data elements, similar to lists, but with the key difference that tuples are immutable, while lists are mutable.

    In addition to indexing, Python provides various other ways to access tuple items such as slicing, negative indexing, extracting a subtuple from a tuple etc. Let us go through this one-by-one −

    Accessing Tuple Items with Indexing

    Each element in a tuple corresponds to an index. The index starts from 0 for the first element and increments by one for each subsequent element. Index of the last item in the tuple is always “length-1”, where “length” represents the total number of items in the tuple. To access the elements of a tuple we just need to specify the index of the item we need to access/retrieve, as shown below −

    tuple[3]

    Example

    Following is the basic example to access tuple items with slicing index −

    Open Compiler

    tuple1 =("Rohan","Physics",21,69.75)
    tuple2 =(1,2,3,4,5)print("Item at 0th index in tuple1: ", tuple1[0])print("Item at index 2 in tuple2: ", tuple2[2])

    It will produce the following output −

    Item at 0th index in tuple1:  Rohan
    Item at index 2 in tuple2:  3
    

    Accessing Tuple Items with Negative Indexing

    Negative indexing in Python is used to access elements from the end of a tuple, with -1 referring to the last element, -2 to the second last, and so on.

    We can also access tuple items with negative indexing by using negative integers to represent positions from the end of the tuple.

    Example

    In the following example, we are accessing tuple items with negative indexing −

    Open Compiler

    tup1 =("a","b","c","d")
    tup2 =(25.50,True,-55,1+2j)print("Item at 0th index in tup1: ", tup1[-1])print("Item at index 2 in tup2: ", tup2[-3])

    We get the output as shown below −

    Item at 0th index in tup1:  d
    Item at index 2 in tup2:  True
    

    Accessing Range of Tuple Items with Negative Indexing

    By range of tuple items, we mean accessing a subset of elements from a tuple using slicing. Therefore, we can access a range of tuple items with negative indexing by using the slicing operation in Python.

    Example

    In the example below, we are accessing a range of tuple items by using negative indexing −

    Open Compiler

    tup1 =("a","b","c","d")
    tup2 =(1,2,3,4,5)print("Items from index 1 to last in tup1: ", tup1[1:])print("Items from index 2 to last in tup2", tup2[2:-1])

    It will produce the following output −

    Items from index 1 to last in tup1: ('b', 'c', 'd')
    Items from index 2 to last in tup2: (3, 4)
    

    Access Tuple Items with Slice Operator

    The slice operator in Python is used to fetch one or more items from the tuple. We can access tuple items with the slice operator by specifying the range of indices we want to extract. It uses the following syntax −

    [start:stop]

    Where,

    • start is the starting index (inclusive).
    • stop is the ending index (exclusive).

    Example

    In the following example, we are retrieving subtuple from index 1 to last in “tuple1” and index 0 to 1 in “tuple2”, and retrieving all elements in “tuple3” −

    tuple1 =("a","b","c","d")
    tuple2 =(25.50,True,-55,1+2j)
    tuple3 =(1,2,3,4,5)
    tuple4 =("Rohan","Physics",21,69.75)print("Items from index 1 to last in tuple1: ", tuple1[1:])print("Items from index 0 to 1 in tuple2: ", tuple2[:2])print("Items from index 0 to index last in tuple3", tuple3[:])

    Following is the output of the above code −

    Items from index 1 to last in tuple1:  ('b', 'c', 'd')
    Items from index 0 to 1 in tuple2:  (25.5, True)
    Items from index 0 to index last in tuple3 ('Rohan', 'Physics', 21, 69.75)
    

    Accessing Sub Tuple from a Tuple

    A subtuple is a part of a tuple that consists of a consecutive sequence of elements from the original tuple.

    We can access a subtuple from a tuple by using the slice operator with appropriate start and stop indices. It uses the following syntax −

    my_tuple[start:stop]

    Where,

    • start is the starting index (inclusive).
    • stop is the ending index (exclusive) of the subtuple.

    If we does not provide any indices, the slice operator defaults to starting from index 0 and stopping at the last item in the tuple.

    Example

    In this example, we are fetching subtuple from index “1 to 2” in “tuple1” and index “0 to 1” in “tuple2” using slice operator −

    tuple1 =("a","b","c","d")
    tuple2 =(25.50,True,-55,1+2j)print("Items from index 1 to 2 in tuple1: ", tuple1[1:3])print("Items from index 0 to 1 in tuple2: ", tuple2[0:2])

    The output obtained is as follows −

    Items from index 1 to 2 in tuple1:  ('b', 'c')
    Items from index 0 to 1 in tuple2:  (25.5, True)
    
  • Tuples

    Tuple is one of the built-in data types in Python. A Python tuple is a sequence of comma separated items, enclosed in parentheses (). The items in a Python tuple need not be of same data type.

    Following are some examples of Python tuples −

    tup1 =("Rohan","Physics",21,69.75)
    tup2 =(1,2,3,4,5)
    tup3 =("a","b","c","d")
    tup4 =(25.50,True,-55,1+2j)

    The empty tuple is written as two parentheses containing nothing −

    tup1 =();

    To write a tuple containing a single value you have to include a comma, even though there is only one value −

    tup1 =(50,);

    Following are the points to be noted −

    • In Python, tuple is a sequence data type. It is an ordered collection of items. Each item in the tuple has a unique position index, starting from 0.
    • In C/C++/Java array, the array elements must be of same type. On the other hand, Python tuple may have objects of different data types.
    • Python tuple and list both are sequences. One major difference between the two is, Python list is mutable, whereas tuple is immutable. Although any item from the tuple can be accessed using its index, and cannot be modified, removed or added.

    Accessing Values in Tuples

    To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

    tup1 =('physics','chemistry',1997,2000);
    tup2 =(1,2,3,4,5,6,7);print("tup1[0]: ", tup1[0]);print("tup2[1:5]: ", tup2[1:5]);

    When the above code is executed, it produces the following result −

    tup1[0]:  physics
    tup2[1:5]:  [2, 3, 4, 5]

    Updating Tuples

    Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −

    tup1 =(12,34.56);
    tup2 =('abc','xyz');# Following action is not valid for tuples# tup1[0] = 100;# So let's create a new tuple as follows
    tup3 = tup1 + tup2;print(tup3);

    When the above code is executed, it produces the following result −

    (12, 34.56, 'abc', 'xyz')
    

    Delete Tuple Elements

    Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.

    To explicitly remove an entire tuple, just use the del statement. For example −

    tup =('physics','chemistry',1997,2000);print(tup);del tup;print("After deleting tup : ");print(tup);

    This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −

    ('physics', 'chemistry', 1997, 2000)
    After deleting tup :
    Traceback (most recent call last):
       File "test.py", line 9, in <module>
    
      print (tup);
    NameError: name 'tup' is not defined

    Python Tuple Operations

    In Python, Tuple is a sequence. Hence, we can concatenate two tuples with + operator and concatenate multiple copies of a tuple with “*” operator. The membership operators “in” and “not in” work with tuple object.

    Python ExpressionResultsDescription
    (1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)Concatenation
    (‘Hi!’,) * 4(‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’)Repetition
    3 in (1, 2, 3)TrueMembership

    Even if there is only one object in a tuple, you must give a comma after it. Otherwise, it is treated as a string.

    Indexing, Slicing, and Matrixes

    Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input −

    L =('spam','Spam','SPAM!')
    Python ExpressionResultsDescription
    L[2]‘SPAM!’Offsets start at zero
    L[-2]‘Spam’Negative: count from the right
    L[1:][‘Spam’, ‘SPAM!’]Slicing fetches sections

    No Enclosing Delimiters

    Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples −

    print('abc',-4.24e93,18+6.6j,'xyz');
    x, y =1,2;print("Value of x , y : ", x,y);

    When the above code is executed, it produces the following result −

    abc -4.24e+93 (18+6.6j) xyz
    Value of x , y : 1 2
    

    Built-in Functions with Tuples

    Following are the built-in functions we can use with tuples −

    Sr.No.Function with Description
    1cmp(tuple1, tuple2)Compares elements of both tuples.
    2len(tuple)Gives the total length of the tuple.
    3max(tuple)Returns item from the tuple with max value.
    4min(tuple)Returns item from the tuple with min value.
    5tuple(seq)Converts a list into tuple.