mutability and immutability in python

Best way when dealing with python is use anaconda 

https://www.anaconda.com/distribution/

will see what is mutability and immutability , for that we wanted to what are available keywords in python, & which came under mutable & which comes and immutable .

 Standard data types

Values can not be changed
==> Immutable Data Types
—-> Number, String,Tuple

Values can be changed
===> Mutable Data Types
—-> List , Dictionary , Set

you may have heard about this familiar words

  1. Everthing is file in Linux
  2. Everthing is module in Ansible
  3. Everthing is resource in Kubernetes ……..

Adding one more to to above Everything in Python is an object.

And those objects can be  either mutable or immutable.

  1. mutable object can be changed after it is created
  2. And an immutable object can’t.

NOTE: When an object is initiated, it is assigned a unique object id. Its type is defined at runtime and once set can never change, however its state can be changed if it is mutable.

There are quite a few data structures available. The builtins data structures are: lists, tuples, dictionaries, strings, sets and frozensets.

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered and unindexed. No duplicate members.
  • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
  • strings are immutable sequence of characters.
  • Sets are mutable, and may therefore not be used, for example, as keys in dictionaries.Another problem is that sets themselves may only contain immutable (hashable) values, and thus may not contain other sets.Because sets of sets often occur in practice, there is the frozenset type, which rep

list = [“apple”, “banana”, “cherry”]
print(list)
[‘apple’, ‘banana’, ‘cherry’]

tuple = (“apple”, “banana”, “cherry”)
print(tuple)
(‘apple’, ‘banana’, ‘cherry’)

set = {“apple”, “banana”, “cherry”}
print(set)
{‘banana’, ‘cherry’, ‘apple’}

dict = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
print(dict)
{‘brand’: ‘Ford’, ‘model’: ‘Mustang’, ‘year’: 1964}

string = “Hello, World!”
print(string[1])
e

a = frozenset([1, 2, 3])
b = frozenset([2, 3, 4])
a.union(b)
frozenset({1, 2, 3, 4})

I will use same table which  most familiar to all .

Image result for mutability and immutability in python

Leave a comment