• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Difference between Mutable and Immutable in Python | Data Types

Aniruddha Chaudhari/60897/12
CodeDifference BetweenPython

Every variable we create in our programming has data types associated with it. This shows the type of value we can save in that variable. These variables can be distinguished into the following major two types in Python – Mutable and Immutable.

Table of Contents

  • What is a Mutable and Immutable Object?
  • Difference between mutable and immutable in Python
  • What are the examples of the Mutable and Immutable Data types in Python?
  • Why is String Immutable if it can be Concatenated?
  • Why is Tuple Immutable Data Type in Python?

What is a Mutable and Immutable Object?

In generic terminology,

A mutable object means an object that can be changed after creating it.

An immutable object means an object that can not be changed once you create it.

The same applies to the Variable.

Difference between mutable and immutable in Python

The variable, for which we can change the value is called a mutable variable.
The variable, for which we can not change the value is an immutable variable.

In the case of Python, both types of variables are available.

If you try to change the immutable object, instead of altering the object, it returns a new object.

What are the examples of the Mutable and Immutable Data types in Python?

All the variables having the following data types are mutable.

  • list
  • dict
  • set
  • bytearray
  • user-defined classes (unless specifically made immutable)

Now examples of Immutable Data types in Python.

All the variables having the following data types are immutable.

  • int
  • float
  • decimal
  • complex
  • bool
  • string
  • tuple
  • range
  • frozenset
  • bytes

You can easily check the datatype of any variable in Python.

Now take some questions.  Getting the answers for these will clear your thoughts on the difference between mutable and immutable in Python.

Why is String Immutable if it can be Concatenated?

Talking about the String mutability, many geeks are confused.

ist_Name =["Bob", "Alley", "Mike"];

str_Output = ""
for data in list_Name:
     string_Output += str(data)

Look at the above program. It is a simple program that concatenates the string. You might be saying; it should be mutable as the string is getting updated.

But internally, it does not update the string; rather it creates the new string. This is all because the string is immutable. It creates a third string by concatenating two strings.

And this is the reason, this code of concatenation is not efficient as it creates a new string every time you call for concatenation.

If you are iterating through the concatenation, lots of memory can be wasted for creating a temporary string and throwing it out after concatenation.

So here is a simple and most effective solution…

list_Name =["Bob", "Alley", "Mike"];

# Another way is to use a
#list comprehension technique in Python
"".join([str(data) for data in list_Name])

It concatenates all the list object values and then converts it into a string. As concatenation occurs at the list (mutable), no new object is created.

Now the second question.

Why is Tuple Immutable Data Type in Python?

If list and dictionary are mutable variables, it’s really confusing as a tuple is immutable. But it is.

Take a list (mutable object) and a tuple (immutable object). Compare what it can be after updating values.

Let’s take an example to prove it by comparing the tuple with the list.

# Create a list variable
list_Num = [5, 7, 9, 11]

# Create a tuple variable (initialize with the same values)
tup_Num = (5, 7, 9, 11)

# print the list
list_Num
[5, 7, 9, 11] # output

# print the tuple
tup_Num
(5, 7, 9, 11) # output

# alter the list (change any value in the list)
list_Num [1] = 6 # success

# alter the tuple (change any value in the tuple)
tup_Num [1] = 4 # error

# print the list again
list_Num
[5, 6, 9, 11] # There is a change in value; so called mutable.

# print the tuple
tup_Num
(5, 7, 9, 11) # None of the values are changed; so it is immutable.

I remember when I attended Druva telephonic interview, they asked me a couple of questions about it.

  • What is the difference between mutable and immutable in Python?
  • What are mutable and immutable variables?

I described it all by giving examples. Then he asked me…

  • If the list is mutable, why is the tuple immutable data type? I was really confused at that time.

Also, check the difference between the tuple and list in Python.

Hope this post clears your doubt. If you have any questions, write in the comment section. I will reply back to you.

Final Words:

  • If you want to write the most efficient code, you should be the knowing difference between mutable and immutable in python.
  • Concatenating string in loops wastes lots of memory. Use the list compression join technique.
  • Though list and tuple seem similar syntactically, the List is mutable and the tuple is an immutable variable in Python.

If you are looking to know more insight about Python, do read the complete Python tutorial. I keep posting my Python tricks there to help you guys.

Happy Programming!

Pythonpython list
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    lokesh
    March 25, 2017 at 4:19 am

    why list is mutable,tuple is immutable.plz explain with example and why values are changed in list,why values are not changed in tuple.

    • Reply
      Aniruddha Chaudhari
      March 25, 2017 at 7:00 am

      Hi Lokesh,

      Many Python programmers find it difficult to understand. So I told its little confusing topic.

      Check out the code in this article under “Why tuple is immutable data type in Python?”

      You can see, in the list, we can change any value. In a case of the tuple, we can not change the value of the object (value) after creating the tuple.

      You can try running the program specified in this post.

  • Reply
    kalyani
    August 28, 2017 at 3:24 pm

    Sir please explain clearly….I have small doubt

    • Reply
      Aniruddha Chaudhari
      August 31, 2017 at 4:57 am

      Hi Kalyani,

      May I know where you are finding it difficult to understand?

  • Reply
    Vikram Sharma
    November 10, 2017 at 3:14 pm

    How python interpreter differentiate mutable and immutable ?

    • Reply
      Aniruddha Chaudhari
      November 10, 2017 at 3:41 pm

      Based on the datatype of the variable you are using. Just as, list and dict are always mutable, the tuple and frozenset are always immutable.

  • Reply
    vaishali
    October 3, 2019 at 5:32 pm

    How can we add or remove an element at a specific index position in a tuple?

    • Reply
      Aniruddha Chaudhari
      October 3, 2019 at 9:52 pm

      You can not add or delete elements from the tuple as it’s immutable.

      However, you can to it indirectly.

      Covert the tuple into a list.
      Add or delete elements from the list
      Convert list back to a tuple.

  • Reply
    venkatesh
    December 19, 2020 at 7:05 pm

    Explained clearly. Thank you!

    • Reply
      Aniruddha Chaudhari
      December 20, 2020 at 8:47 am

      You’re welcome, Venkatesh. Glad you like it.

  • Reply
    Rajak
    September 12, 2022 at 8:11 pm

    Maybe mutable means we can change a variable without changing the id of the variable/object.

    • Reply
      Aniruddha Chaudhari
      September 21, 2022 at 10:35 pm

      Exactly. You are right, Rajak.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard