Difference between Mutable and Immutable Sequences in Python
September 14, 2023
Difference Between Mutable and Immutable Sequence in Python
The main difference between these two is that a mutable sequence can be changed after its creation while an immutable sequence can not change. Most Common Mutable Sequences in python are List, Set and Dictionary and most common immutable sequence in python are tuple and string.
What is a Sequence Type?
If we talk about sequences in Python, these are two forms:
Mutable sequence type
Immutable sequence type
Mutable Sequence vs Immutable Sequence
Mutable Sequence Type
Immutable Sequence Type
Mutable Sequence can be modified after its creation by performing easy operations like append, delete, update.
Immutable sequence can’t be modified once created but it can be altered by making a copy with the updated data.
Mutable Sequences are easy to update hence are less secure.
Immutable Sequence are a more secure option to store data as it can’t be changed after creation.
Mutable sequence are slower in terms of access as compared to immutable sequence.
Immutable Sequences are quicker to access than mutable sequences.
Use of mutable sequence is recommended when we want to change data(content) or size dynamically.
Use of an immutable sequence is recommended when we want more security for our data.
Operations supported by Mutable Sequence Type
The main difference that makes mutable sequence type different from immutable sequence type is that it supports multiple operation that allows modification after it’s creation. The following operations are described for mutable sequences (where x is an arbitrary object):
Operations on Mutable Sequence
Change after performing Operation
s[i] = x
ith item of sequence “s” is replaced by “x”
s[i:j] = t
replaces a slice of “s” from i index to j index with “t”
del d[i:j]
(same as s[i:j] = [])
deletes a slice of “s” from i index to j
s.append(x)
adds x to sequence in last
s.extend(x)
this is used only to extend list, it adds a list to existing list and also throws an exception if x is not a list object
s.count(x)
returns number of occurrences of x in sequence
s.index(x)
returns the first index where x is encountered
s.insert(i, x)
inserts x at i index in sequence
s.pop([i])
removes object at i index from sequence it also returns the object which is removed
The main difference that makes mutable sequence type different from immutable sequence type is that it supports multiple operation that allows modification after it’s creation. The following operations are described for mutable sequences (where x is an arbitrary object):
Operations on Immutable Sequence(tuple)
Change after performing Operation
t[x]
returns the element at index ‘x ‘of tuple ‘t’.
t[i:j]
returns a slice of “t” from ith index to jth index
del t
deletes whole tuple ‘t’
t.count(x)
returns number of occuring of ‘x’ in tuple ‘t’
t.index(x)
returns the index at which object ‘x’ is situated in tuple ‘t’
Login/Signup to comment