Tuples in python

                                   Tuples in python

Tuples are similar to list . It is the sequence of immutable python objects . The main difference between list and tuples is that the tuples cannot be changed after it is defined whereas in we can change. The tuple are defined using parentheses () .

Defining a tuple

Creating a tuples is very easy .  We have to just put the object inside the parentheses and seperate each object by comma . A tuple look likes :

subject  = ( 'dbms' ,'os' , 'cn');
marks = (70, 50 ,60);
avg = (70,);

Accessing Values in tuples

We can access the value from tuple by putting the index of element of which we want inside square brackets along with tuple name . The example given below will illustrate  this:

subject  = ( 'dbms' ,'os' , 'cn');
marks = (70, 50 ,60);
avg = (70,);
print (subject[0:2]);
 print (avgt[0]);

Output  

 ('dbms', 'os', 'cn')   
 (70)


Deleting tuple elements 

Removal of an individual elements from a tuple is not possible , but we can remove entire tuple using del statement .  The example given below will illustrate  this:

subject  = ( 'dbms' ,'os' , 'cn');
del subject ;
print(subject[0:2]) ;

Output
Traceback (most recent call last):                                
  File "/home/main.py", line 5, in <module>                       
    print(subject[0:2]) ;                                         
NameError: name 'subject' is not defined


Built-in tuple functions

Tuples in python provide some useful built-in functions . Some of the built-in function is listed below:

  • len(tuplename) : It provides the length of tuples.
  • cmp(tuple1 , tuple 2 ) : Its compare the elements of both tuples.
  • tuple(sequencename) : It convert a list into tuple.
  • max(tuplename) : It provides the maximum value element from tuple.
  • min(tuplename) : It provides the minimum value element from tuple.



Comments