Python Data Types (Mutable vs Immutable)

Vrushali Chaudhari
2 min readSep 1, 2020

--

Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are object of these classes.

There are various data types in Python. Some of the important types are listed below.

  • Numbers
  • Strings
  • List
  • Tuple
  • Dictionary

Numbers :- Number data type store numeric value. Number objects are created when you assign value to it. Numbers are immutable.

eg. var1=10

Python supports four different numerical types

a)int b)long c)float d)complex

String :- Strings are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ( [ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.Strings are immutable

eg. str=’Python’

Lists :- A list contains values separated by comma and enclosed within square bracktes([]).We can say lists are similiar to array only one difference that list contains values of different data type. Lists are mutable meaning the value of list can be changed.

eg. list = [ ‘xyz’, 55, 5.53 ]

Tuples :- Tuple data type is similar to the lists. The difference between lists and tuples are: Lists are enclosed in brackets ([ ]) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Another main difference between lists and tuples is tuples are immutable. Once tuple created can not changed or modified.

eg. tuple = ( ‘xyz’, 55, 5.53 )

Dictionary :- Dictionary is an unordered collection of key - value pair. Dictionaries generally used when we have large amount of data. Dictionaries are optimized for retrieving data. We can retrieve value using the key.

Dictionaries are enclosed within braces ({}) with each item being a pair in the form of key:value. Key and value can be of any type. Dictionaries are mutable

eg. dict={1:’first’,2:’second’}

Difference Between Mutable and Immutable Data Types

As we know that “Everything in Python is an object”. Every object in python has an ID(Identity), a type, and a value.

a) Once created the ID of an object never changes. It is a unique identifier for it, and it is used to retrieve the object when we want to use it.

b) The type also never changes. The type tells what operations are supported by the object and the possible values that can be assigned to it.

c) The value can either change or not. If value can change, the object is said to be mutable, and when value cannot change, the object is said to be immutable.

Mutable Data Types: lists,sets, dictionaries and byte arrays

Immutable Data Types: Numeric datatypes, strings,tuples,frozen sets,bytes

--

--