Monday, March 27, 2017

Tuple in Python

Tuple is like a list. Only difference is it's immutable whereas list is mutable. What it means is that one can change the elements of a list after initial assignment, however the elements of the tuple can't be changed. Tuple in that sense provides a write protection guarantee.

#Create a tuple of Country and Capital and we don't want to change it
#Note that tuple use parenthesis for definition
>>>tuple = (['India','Delhi'],['USA','Washington'],['Germany','Berlin'])

#Trying to change the tuple element fail
>>> tuple[0] = ['India','Pune']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

#accessing element of tuple
>>> tuple[0]
['India', 'Delhi']

#accessing sub-element of tuple
>>> tuple[0][1]
'Delhi'

#be careful you can change sub-element
>>> tuple[0][1] = 'Pune'
>>> tuple
(['India', 'Pune'], ['USA', 'Washington'], ['Germany', 'Berlin'])



No comments:

Post a Comment