Showing posts with label python tuple tutorial. Show all posts
Showing posts with label python tuple tutorial. Show all posts

Thursday, August 20, 2015

Can Tuple be Modified in Python?

The basic and obligatory purpose of creating a tuple is that it can not be modified. The concept and motive behind tuple creation is to get sturdy solid list which can not be modified by any means; if not so, there is no obligation to use the list instead of tuple.  For better understanding lets create a tuple and hit dir(tuple name) e.g.
>> tuply=('me','us','you','them')
>>dir(tuply)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

As you can see we have only two common methods with list, they are count and index. Both the methods are self explanatory and described in here.
Obviously , we can not destroy tuple elements in any way. If we want to keep the tuple we need to keep the contents too. As they say non-modifiable, But!! look there is a first option in the dir(tuply) output, __add__(), is that be used to modify the tuple i.e. by adding new entry to the tuple? 

Lets try this  - 
>> tuply.__add__("all")
Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    tuply.__add__('all')
TypeError: can only concatenate tuple (not "str") to tuple 

 Looks like we have a trace back, So, I need to have to add only tuple to tuple and not a string can be added to the tuple. So lets do this  - 
>> tuply.__add__(('all'))
 This is giving the same traceback; One of the expert told me that there will be a comma after the new entry. So lets give the comma and run it - 
>> tuply.__add__(('all',))
('me','us','you','them','all')
Hoops!!!! At last we have successfully modified the tuple entry. But it is really modification of the same tuple or we are destroying the old one and creating  a  new one? What do you think -let me know by commenting.
We can also add something to the beginning of the tuple in stead of to the last , by doing this -  Or, lets join them with 'love' -

>>  tuply = ('love',) + tuply
 ('love','me','us','you','them','all')
 Also visit my website www.pythonbeginner.in and subscribe there to get free eBook and online solution to your python related prob;ems.



  
   

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...