Python Objects: Lists: Mutation of List




Lists are almost same as Tuples, but a huge difference is, Lists are mutable i.e. Lists can be modified after they are created unlike Tuples and Strings

For example, consider a Tuple:


>>> t1 = (1,'two',3)
>>> t1
(1, 'two', 3)
>>> t1[1]
'two'
>>> t1[1] = 2 #trying to replace 'two' by 2
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    t1[1] = 2
TypeError: 'tuple' object does not support item assignment


Same error while mutating a String.

>>> s1 = 'Kate'
>>> s1[0]
'K'
>>> s1[0] = 'M' #trying to replace 'K' by 'M'
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    s1[0] = 'M'
TypeError: 'str' object does not support item assignment


That is why we have Lists

>>> l1 = [1,'two',3] #List is declared in between [] unlike Tuple ()
>>> l1
[1, 'two', 3]
>>> l1[1]
'two'
>>> l1[1] = 2
>>> l1
[1, 2, 3]


Declaring a Singleton List

>>> l2 = [4] #No comma operator required unlike Tuple >>> t2 = (4,)
>>> l2
[4]
>>> type(l2)
<type 'list'>


Important! Understand the difference between Assigning a List and Copying a List

>>> l1 = [1,2,3]
>>> l2 = l1 #This is called Assignment. List l1 is assigned to l2
>>> l3 = l1[:] #This is called Copying. List l1 is copied into l3
>>> l1[2] = 'three'
>>> l1
[1, 2, 'three']
>>> l2
[1, 2, 'three']
>>> l3
[1, 2, 3]


Here, we are confused, Why is only l2 affected and not l3.
That is because, l2 points to the address of l1 in computer memory, but l3 is created as a whole new list and acquires specific memory units that contains all the elements of l1. Have a glance of it here.

Mutation of List
Related Articles:
Python Objects: Dictionary (dict)
Python Objects: Strings and Operations on Strings
Python Objects: Tuples and its use

Note:
This is a part of what I learn in an online Open Course Ware offered by MIT on edX
Its for my personal reference & also for those who have missed the course.
You too can enroll yourself on edX (if they are still offering the course MITx 6.00x)