python


Python Tuple


Tuples

A Tuple can be defined as a ordered collection of objects which are immutable.

Tuples are also sequences just like lists.But the main difference between these 2 is lists are mutable(can be changed) but tuples are immutable(cannot be changed) unlike lists.
Tuples uses parentheses().

Example:
tup1=('Computer','Laptop',30,70);
tup2=(1,2,3,4,5);
tup3=(50,);    # a single valued tuple also contain comma(,)

To create an empty tuple:

tup1=();

Like strings, tuple index also starts from 0 and they can be sliced,concatenated and so on.


Accessing tuple values

To access the tuple values,we use the square brackets[ ] for slicing along with the index or indices to obtain value available at the index.It is similar to string.


Example:
tup1=('Computer','Laptop',30,70);
tup2=(1,2,3,4,5);
print(tup1[0])
print(tup2[3])
Output:
Computer
4

Slicing can also be used in tuples as mentioned above.Let's take an example:


Example:
tup3=(12,23,34,45,56,67,78,89);
print(tup3[3:7])
Output:
[45,56,67,78]
Updating Tuples

As said earlier,tuples are immutable that means it cannot be changed or updated.You can see below what happens if we try to change the tuple variable.

tuples are immutable
Deleting Tuple

Deletion of tuple elements is not possible because tuples are immutable.However, the entire tuple can be deleted by keyword del.It deletes the entire tuple.

tup1=('Computer','Laptop',30,70);
print(tup1)
del tup1

The above code will remove the entire tuple.

Built-in Tuple functions
  1. len(tuple1)
    This function will give the total length of the tuple.
    Code:
    tup3=(12,23,34,45,56,67,78,89);
    print(len(tup3))
    
    Output:
    8
    
  2. max(tuple)

    This function will return the item with maximum value from the tuple.

    Code:
    tup3=(12,23,34,45,56,67,78,89);
    print(max(tup3))
    
    Output:
    89
    
  3. min(tuple)

    This function will return the item with minimum value from the tuple.

    Code:
    tup3=(12,23,34,45,56,67,78,89);
    print(min(tup3))
    
    Output:
    12
    
  4. tuple(seq)

    This function is used to convert a list into a tuple.

  5. cmp(tuple1,tuple2) This function is used to compare the elements present in the both tuples.

Basic Tuple operations:
table of tuple operations