Python Tuples

                                 Tuples

Just like list in Python, Tuple is also used to store the data but the difference is that tuples are unchangeable. Tuples are also ordered. We use round brackets or paranthesis to represent tuple. 
E.g. tup1 = ('one', 'two', 'three')
Tuple is indexed same as lists. We can access the elements of tuple by using index strtaing from 0.
E.g. print(tup1[1])          # output : two

Negative indexing means we start from the end of tuple just like list. -1 means last element, -2 means secod last and so on.
E.g.  tup2 = (10, 25, 31, 36, 67)
    print(tup2[-1])        #output : 67
    print(tup2[-3])        #output : 31

To check the length of tuple we can use len() method.
E.g. len(tup2)          # output : 5

As we already discussed that tuplea are unchangeable so we can not add or remove the items. But we can join two tuples using + operator.
E.g.  tup3 = (1, 3, 5)
    tup4 = (7, 2, 9) 
    tup5 = tup3 + tup4      # output: tup5 = (1, 3, 5, 7, 2, 9)

tuple() function is the constructor w used to make a tuple. 
E.g. tup6 = tuple((100, 200, 300))
    print(tup6)       #output : (100, 200, 300)

del() function is used to delete the tuple.
E.g. del(tup1)

We can so the indexing od tuple just like lists.
E.g.    print(tup2[2:4])          #output : (31, 36)
       print(tup2[3:])            #output : (36, 67)
       print(tup2[:4])            #output : (10, 25, 31, 36)
       print(tup2[-3:])          #output : (31, 36, 67)
       print(tup2[:-2])          #output : (10, 25, 31)

We can find out the maximum and minimum from the tuple using max() and min() function.
E.g.        max(tup5)         #outout : 9
       min(tup5)          #output : 1

Tuple is similar to list but provides less functionality so we can use tuple in the cases where we need read-only data type. We can loop through the tuple, can find the existence of item in tuple, can access the values, can do slicing, delete the tuple but we can not change it means add or remove the elements.

Comments

Popular posts from this blog

Loops in Python

Python OOPs

Regular Expressions