Mutable Sequence Types in Python

mutable-sequence-types

Mutable Sequence Types

  • List
  • Dictionary
  • Set

 
Mutable and immutable objects are treated differently in python. Immutable objects are faster to access and are costlier to change because it needs the creation of a copy.
Whereas mutable objects are easy to change.

In Python the data structure or we can say sequences are defined into two categories –

  • Mutable Sequences
  • Immutable Sequences

Mutable sequences can be changed after their creation while immutable sequences can’t be updated however there are some tricks to update the immutable sequences. So, due to above characteristics it can be referred as immutable sequences are read-only and mutable sequences are both read and write compatible.

List

>>> companies = ['tata','wipro','accenture']
>>> companies
['tata', 'wipro', 'accenture']
>>> companies[0]='tcs'
>>> companies
['tcs', 'wipro', 'accenture']
>>> companies[-1]='cognizant'
>>> companies
['tcs', 'wipro', 'cognizant']

Dictionary

>>> dictionary1 = {'Prep':'Insta', 1:'Myname'}
>>> dictionary1
{'Prep': 'Insta', 1: 'Myname'}
>>> dictionary1['Prep']='PrepInsta'
>>> dictionary1
{'Prep': 'PrepInsta', 1: 'Myname'}
>>> dictionary1[0]='Prep'
>>>dictionary1
{'Prep': 'PrepInsta', 1: 'Myname', 0: 'Prep'}

Set

>>> set1=set(companies)
>>> set1
{'wipro', 'tcs', 'cognizant'}
>>> set1.add('accenture')
>>> set1
{'accenture', 'wipro', 'tcs', 'cognizant'}