Python: Mutable, Immutable. Everything is object. Yes, including that.
Python, Objects, and You.

Python: Mutable, Immutable. Everything is object. Yes, including that.


Introduction

What you read in this article will not be ground breaking information. It will not change worlds. It's nothing that hasn't been said before. And for that dear reader, I apologize. However, I hope I can give my perspective on Objects and what I have learned from this project, and that you may get something from it. Python is to Objects what Salt is to French Fries. Would you eat unsalted French Fries? I didn't think so. Let's get into it.

ID and Type

ID and Type. Seems pretty straight forward right? After all, the mantra for Python is "Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts". In summary, There should be one simple way of doing one thing. So what does ID and Type do? Well I'm glad you asked.

Id and Type are a part of a vast array of built in functions in Python. Their respective uses vary, and they are useful. To reiterate, ID and Type = built-in functions.

How do I use them?

Let's start with Id.

BenIsAwesome = 1991
print(id(BenIsAwesome))         

In this example, I've created a variable (BenIsAwesome) and assigned it a value (1991). If I wanted to know the ID of said variable, and since I am human and would need visual representation of it, I would use the 'print' function, referencing the ID function, and the variable I'm curious to know the Id of. Pretty simple right? Let's test this on my local

Article content
The code I referenced above, in VS Code.


Running this program, I get the following results.

Article content
I see the output from print(id())

So what is id()? id() returns the memory address of whatever you pass. There are several use-cases for id(), such as debugging and development, comparing an object's identity, or caching. This is a very low-level explanation of id() and how to use it, but I hope you find it useful.

Additionally, if I run this program multiple times, I get different references for the id as follows

Article content
Different results any time it's ran

Why is that? Well it's because any time you run a program in python, It's taking what you are passing and assigning the respective values and types to their place in memory. Once that program is finished, that program's values are destroyed and free's up that space in memory. So when I run it again, it's assigned a new block of memory which would have a different id() value. Neat!

Type

Type is also part of Pythons vast array of built-in functions. If you can imagine, it is used to return the Type of an object. Amazing right? I think so. Let's see what type BenIsAwesome is! Again, since I'm human, I need visual representation to understand, so what should I do?

That's right! Use the print function!

BenIsAwesome = 1991
print(type(BenIsAwesome))        

So in this example we are just changing the print function to use the Type function, instead of ID. Let's see what we get!

Article content
It's an int! Surprised? I'm not.

So as we can see, we have visual representation as to what type BenIsAwesome is. Because I used '1991' as the value, it would be an integer. Let's switch some things up!

BenIsAwesome = True
print(type(BenIsAwesome))        

The following is our result;

Article content
Results!

We can now see that our type() has changed from 'int' (integer) to 'bool' (boolean). Boolean values are at it's core, on or off. Yes/no, True/False, 1/0, On/Off. So as we change our type, we can see that reflection in its result. Nifty!

Type() can be a very useful tool from a Programmer's standpoint. If you aren't getting the results that you desire, it's easier to start from the basics to see where your wires are crossed, and using Type() is a very effective way to compare multiple things to make sure what code you are using is producing the results you desire.

Mutable, Immutable, and what does that even mean?

Mutable and Immutable is a whole new concept to me, so I will do my best to articulate my understanding. Let's start with Mutable.

Mutable: Mute-Able. Able to Mute if you will. 'Mutable' essentially refers to Objects whose state (or content) can be changed after they are created. In lament terms, If an Object is mutable, it's changeable. Some examples of this would be Lists, Dictionaries, and Sets. Let's explore!

pers_dict = {"name": "Ben", "age": 33, "city": "Tulsa", "favteam": "Bears"}        

Above, I have created a dictionary named pers_dict. It has Name, Age, City, and Favteam. Let's print it first so you can see the value of my dictionary.

Article content
Here is the result from pers_dict

Now what if I wanted to change it? Since it's a mutable object, I am able! Let's add a line to the program that would add an entry to my dictionary, and print the updated results.

pers_dict = ["school"] = "Atlas"         
Article content
I added an item to my Mutable object!

As you can see, I created a new dictionary entry with a value to pers_dict, a mutable object! For funsies, let's see what our Id and type values are for our Mutable object!

Article content
We have results!

Here we can see the Id() and type() of our mutable object. I can see that our object type is 'dict', which is short for dictionary, which is correct!

After making that change to pers_dict, anything else that would reference pers_dict down the line would also get the updated change. Neato!

Immutable. Im-mute. Unable. Immutable simply means a value that can't be changed. Immutable objects are objects that once created, will always remain. infinite, Fixed, Constant, Steadfast, Enduring, Unmodif... I think you get it.

In Python, there are several different types which are Immutable. Integers, Floats, Strings, Tuples, and Booleans are several of the different types which are immutable. Let's dive in.

That_Which_Is_True = "Ben is Awesome"        

Here I have created a simple string (That_Which_Is_true) and have given it the value of, "Ben is Awesome". Let's see it in action.

Article content
They say no code is perfect, but I disagree.

There we have it. A string, with a value, that print's beautifully. So given the fact that we know it's a string, and we know it's Immutable, what happens when I try to change it? I think we know the outcome, but let's find out in the name of science. In an attempt to alter my string, I'll do a little something like this

That_Which_Is_true[7]="NOT "        

When putting this code into action, this is the result;

Article content
We receive an an error!

We get an error. An Error that declares, Object does not support item assignment. In other words, Immutable! Now, you may be thinking to yourself, it does say item so maybe it's looking for a specific entry, not an entire word and to that I say

Article content
You would be wrong.

Immutable = Immutable. Period.

Immutable items do have their uses. You wouldn't want yourself, other developers, or even users to make changes to things that should never be changed, or things you know will never change (at least anytime soon). For instance, time zones, certain temperatures (Freezing won't ever be anything other than 32.0, right?) Or even the coordinates 38.8977° N, 77.0365° W wouldn't change any time soon. I hope...

Now, let's take a step back, maybe even take a coffee break, before we put everything together and try to put together what I (and hopefully you, while reading this) have learned!

Why Does this matter?

When you have a mutable object, whenever you make changes to that object Python more often or not makes changes to that object in its same location. Meaning, if you ran id() on a dict you would receive its memory location. Make a change to it, and run id() on it again, it more than likely will be in its original location! What this also means is, anything referencing that object will also be referencing the original object in its same location, with its new data. If we go a step further, In terms of memory management and processing speed, it's quicker to edit a mutable object in it's original location than it is to duplicate it, taking up more spaces. Now, we're probably talking bytes here, but in the grand scheme of things, every single byte adds up in the long run.

Immutable objects, if any attempt is made to an immutable object, Python creates a new object with the original object data and you are in fact, editing the new object, not the original. More objects on top of the original object = more memory. More memory the program takes = less memory available to use elsewhere. Additionally, if you unknowingly make a change to an immutable object and Python creates a new object, anything down the line will NOT be referencing the new object, so any changes you think you have made you have in fact, not made. Makes sense?

Summary

Well here we are. I hope you enjoyed our time together. By now I hope I have instilled in you that in Python, everything is an Object. It's vastly important to understand the differences between Immutable and Mutable objects and their respective functions, but in the end it's not rocket surgery. I hope you found these words educational, entertaining and insightful.

Happy coding!





To view or add a comment, sign in

More articles by Benjamin Carter

  • Capstone and Beyond

    The last month I've been working on my final project for Atlas School, a project that once I heard about it I knew I…

    1 Comment
  • Lets talk about Python!

    I'm going to be honest, when I started Atlas School over a year ago the only thing I knew about Python was that it was…

  • AI and Us: Understanding the Present and Predicting the Future.

    A few weeks ago I attended an event about artificial intelligence (AI) at 36 Degrees North. The event explored how AI…

    1 Comment
  • Time Off: Take it.

    The average life expectancy according to the CDC as of this article, is 77.5 years(1) The average retirement age in…

  • Atlas - Hack Sprint Retrospective

    A Mysterious Beginning Focus To create a point and click style game in Godot to showcase our developmental skills…

    1 Comment

Others also viewed

Explore content categories