Tuples





Hello Folks....!!!

Today's topic is 'Tuples' in python

The tuples are same as lists in python except int these two things:
  • Lists are mutable but tuples are immutable.
  • Lists are enclosed within '[]' but tuples '()'.
The tuples are accessed using their index. They also have reverse index(negative index).

What is meant by immutable..?

In lists, we can make change the contents of lists at any point, ie., we can update it at any point of the program. But tuples once initialized with a value cannot be changed/updated. That is why they are known to be immutable objects of python.

Declaring and initializing a tuple :

To just declare an empty tuple :
tup1=()

To initialize values :
tup1=('a',1,23,'python')

Like lists tuples can also be heterogeneous. It is not necessary that they must contain only values of same data type.

Methods associated with tuples :

1. len() Gives the length of a tuple. The syntax is len(tuple_name).

2. max(tuple_name) : Gives the maximum element in the tuple.

3. min(tuple_name) : Gives the minimum element in the tuple.

4. tuple() : This can be used to convert a list into tuple. The list name has to be passed as an argument.

5. cmp(tup1,tup2) : To compare two tuples. If two tuples contain same elements then it returns '1' else '-1'.

Slicing technique : Like lists, tuples can also be sliced using the index. Recall about this from this link.  
Note : To apply max() and min() methods the tuple must be homogeneous.Otherwise you will get error. Look at the example below :

tuples-python

Here the tuple contains different types of elements, that is why error is generated. That is why I spliced the tuple and passed it to the method, which did not produce any error.

Consider the following :

  • Tuple Concatenation :

        tup1=(1,3,5)
        tup2=('w','f','b')
        tup3=tup1+tup2


         This results in concatenation and the output will be 
                     tup3=(1,3,5,'w','f','b').

  • Tuple Repetition

            If you write tup1=(4)*5, the resultant tuple will be like tup1=(4,4,4,4,4).

    Thatsall about tuples.....

    Next Topic👉

    Comments