Objek yang Dapat Diubah vs Tidak Dapat Diubah dengan Python - Panduan Visual dan Praktis

Python adalah bahasa yang luar biasa. Karena kesederhanaannya, banyak orang memilihnya sebagai bahasa pemrograman pertama mereka.

Pemrogram berpengalaman juga menggunakan Python sepanjang waktu, berkat komunitasnya yang luas, banyaknya paket, dan sintaks yang jelas.

Tetapi ada satu masalah yang tampaknya membingungkan pemula serta beberapa pengembang berpengalaman: Objek Python. Secara khusus, perbedaan antara objek yang bisa berubah dan objek yang tidak bisa diubah .

Dalam posting ini kita akan memperdalam pengetahuan kita tentang objek Python, mempelajari perbedaan antara objek yang bisa berubah dan objek yang tidak bisa diubah , dan melihat bagaimana kita bisa menggunakan interpreter untuk lebih memahami bagaimana Python beroperasi.

Kami akan menggunakan fungsi dan kata kunci penting seperti iddan is, dan kami akan memahami perbedaan antara x == ydan x is y.

Apakah Anda siap untuk itu? Mari kita mulai.

Di Python, semuanya adalah objek

Tidak seperti bahasa pemrograman lain yang bahasanya mendukung objek, dalam Python sebenarnya semuanya adalah objek - termasuk bilangan bulat, daftar, dan bahkan fungsi.

Kami dapat menggunakan penerjemah kami untuk memverifikasi bahwa:

>>> isinstance(1, object) True >>> isinstance(False, object) True def my_func(): return "hello" >>> isinstance(my_func, object) True

Python memiliki fungsi built-in id, yang mengembalikan alamat suatu objek dalam memori. Sebagai contoh:

>>> x = 1 >>> id(x) 1470416816

Di atas, kami membuat sebuah objek dengan nama x, dan memberinya nilai 1. Kami kemudian menggunakan id(x)dan menemukan bahwa objek ini ditemukan di alamat 1470416816di memori.

Ini memungkinkan kami untuk memeriksa hal-hal menarik tentang Python. Katakanlah kita membuat dua variabel dengan Python - satu dengan nama x, dan satu lagi dengan nama y- dan memberikan nilai yang sama. Contohnya disini:

>>> x = "I love Python!" >>> y = "I love Python!"

Kita bisa menggunakan operator persamaan ( ==) untuk memverifikasi bahwa mereka memang memiliki nilai yang sama di mata Python:

>>> x == y True

Tetapi apakah ini objek yang sama dalam memori? Secara teori, mungkin ada dua skenario yang sangat berbeda di sini.

Menurut skenario (1) , kita sebenarnya memiliki dua objek yang berbeda, satu dengan nama x, dan satu lagi dengan nama y, yang kebetulan memiliki nilai yang sama.

Namun, bisa juga menjadi kasus bahwa Python sebenarnya hanya menyimpan satu objek, yang memiliki dua nama yang mereferensikannya - seperti yang ditunjukkan dalam skenario (2) :

Kita dapat menggunakan idfungsi yang diperkenalkan di atas untuk memeriksanya:

>>> x = "I love Python!" >>> y = "I love Python!" >>> x == y True >>> id(x) 52889984 >>> id(y) 52889384

Jadi seperti yang bisa kita lihat, skenario kecocokan perilaku Python (1) yang dijelaskan di atas. Meskipun x == ydalam contoh ini (yaitu, xdan ymemiliki yang sama nilai-nilai ), mereka objek yang berbeda dalam memori. Ini karena id(x) != id(y), seperti yang dapat kami verifikasi secara eksplisit:

>>> id(x) == id(y) False

Ada cara yang lebih singkat untuk membuat perbandingan di atas, dan itu adalah dengan menggunakan isoperator Python . Memeriksa apakah x is ysama dengan memeriksa id(x) == id(y), yang berarti apakah xdan yadalah objek yang sama di memori:

>>> x == y True >>> id(x) == id(y) False >>> x is y False

Ini menjelaskan perbedaan penting antara operator kesetaraan ==dan operator identitas is.

Seperti yang Anda lihat pada contoh di atas, sangat mungkin bagi dua nama dalam Python ( xdan y) untuk terikat ke dua objek yang berbeda (dan dengan demikian, x is yadalah False), di mana kedua objek ini memiliki nilai yang sama (begitu x == yjuga True).

Bagaimana kita bisa membuat variabel lain yang menunjuk ke objek yang sama yang xdituju? Kami hanya dapat menggunakan operator penugasan =, seperti:

>>> x = "I love Python!" >>> z = x

Untuk memverifikasi bahwa mereka memang menunjuk ke objek yang sama, kita dapat menggunakan isoperator:

>>> x is z True

Tentu saja, ini berarti mereka memiliki alamat yang sama di memori, karena kami dapat memverifikasi secara eksplisit dengan menggunakan id:

>>> id(x) 54221824 >>> id(z) 54221824

Dan, tentu saja, mereka memiliki nilai yang sama, jadi kami berharap x == zuntuk kembali Truejuga:

>>> x == z True

Objek yang bisa berubah dan tidak bisa diubah dengan Python

Kami telah mengatakan bahwa segala sesuatu di Python adalah sebuah objek, namun ada perbedaan penting antar objek. Beberapa objek bisa berubah sementara beberapa tidak bisa diubah .

Seperti yang saya sebutkan sebelumnya, fakta ini menyebabkan kebingungan bagi banyak orang yang baru mengenal Python, jadi kami akan memastikannya jelas.

Objek yang tidak bisa diubah dengan Python

Untuk beberapa jenis di Python, setelah kita membuat contoh jenis tersebut, mereka tidak pernah berubah. Mereka tidak bisa diubah .

Misalnya, intobjek tidak dapat diubah dengan Python. Apa yang akan terjadi jika kita mencoba mengubah nilai suatu intbenda?

>>> x = 24601 >>> x 24601 >>> x = 24602 >>> x 24602

Well, it seems that we changed x successfully. This is exactly where many people get confused. What exactly happened under the hood here? Let's use id to further investigate:

>>> x = 24601 >>> x 24601 >>> id(x) 1470416816 >>> x = 24602 >>> x 24602 >>> id(x) 1470416832

So we can see that by assigning x = 24602, we didn't change the value of the object that x had been bound to before. Rather, we created a new object, and bound the name x to it.

So after assigning 24601 to x by using x = 24601, we had the following state:

And after using x = 24602, we created a new object, and bound the name x to this new object. The other object with the value of 24601 is no longer reachable by x (or any other name in this case):

Whenever we assign a new value to a name (in the above example - x) that is bound to an int object, we actually change the binding of that name to another object.

The same applies for tuples, strings (str objects), and bools as well. In other words, int (and other number types such as float), tuple, bool, and str objects are immutable.

Let's test this hypothesis. What happens if we create a tuple object, and then give it a different value?

>>> my_tuple = (1, 2, 3) >>> id(my_tuple) 54263304 >>> my_tuple = (3, 4, 5) >>> id(my_tuple) 56898184

Just like an int object, we can see that our assignment actually changed the object that the name my_tuple is bound to.

What happens if we try to change one of the tuple's elements?

>>> my_tuple[0] = 'a new value' Traceback (most recent call last): File "", line 1, in  TypeError: 'tuple' object does not support item assignment

As we can see, Python doesn't allow us to modify my_tuple's contents, as it is immutable.

Mutable objects in Python

Some types in Python can be modified after creation, and they are called mutable. For example, we know that we can modify the contents of a list object:

>>> my_list = [1, 2, 3] >>> my_list[0] = 'a new value' >>> my_list ['a new value', 2, 3]

Does that mean we actually created a new object when assigning a new value to the first element of my_list? Again, we can use id to check:

>>> my_list = [1, 2, 3] >>> id(my_list) 55834760 >>> my_list [1, 2, 3] >>> my_list[0] = 'a new value' >>> id(my_list) 55834760 >>> my_list ['a new value', 2, 3]

So our first assignment my_list = [1, 2, 3] created an object in the address 55834760, with the values of 1, 2, and 3:

We then modified the first element of this list object using my_list[0] = 'a new value', that is - without creating a new list object:

Now, let us create two names – x and y, both bound to the same list object. We can verify that either by using is, or by explicitly checking their ids:

>>> x = y = [1, 2] >>> x is y True >>> id(x) 18349096 >>> id(y) 18349096 >>> id(x) == id(y) True

What happens now if we use x.append(3)? That is, if we add a new element (3) to the object by the name of x?

Will x by changed? Will y?

Well, as we already know, they are basically two names of the same object:

Since this object is changed, when we check its names we can see the new value:

>>> x.append(3) >>> x [1, 2, 3] >>> y [1, 2, 3]

Note that x and y have the same id as before – as they are still bound to the same list object:

>>> id(x) 18349096 >>> id(y) 18349096

In addition to lists, other Python types that are mutable include sets and dicts.

Implications for dictionary keys in Python

Dictionaries (dict objects) are commonly used in Python. As a quick reminder, we define them like so:

my_dict = {"name": "Omer", "number_of_pets": 1}

We can then access a specific element by its key name:

>>> my_dict["name"] 'Omer'

Dictionaries are mutable, so we can change their content after creation. At any given moment, a key in the dictionary can point to one element only:

>>> my_dict["name"] = "John" >>> my_dict["name"] 'John'

It is interesting to note that a dictionary's keys must be immutable:

>>> my_dict = {[1,2]: "Hello"} Traceback (most recent call last): File "", line 1, in  TypeError: unhashable type: 'list'

Why is that so?

Let's consider the following hypothetical scenario (note: the snippet below can't really be run in Python):

>>> x = [1, 2] >>> y = [1, 2, 3] >>> my_dict = {x: 'a', y: 'b'}

So far, things don't seem that bad. We'd assume that if we access my_dict with the key of [1, 2], we will get the corresponding value of 'a', and if we access the key [1, 2, 3], we will get the value 'b'.

Now, what would happen if we attempted to use:

>>> x.append(3)

In this case, x would have the value of [1, 2, 3], and y would also have the value of [1, 2, 3]. What should we get when we ask for my_dict[[1, 2, 3]]? Will it be 'a' or 'b'? To avoid such cases, Python simply doesn't allow dictionary keys to be mutable.

Taking things a bit further

Let's try to apply our knowledge to a case that is a bit more interesting.

Below, we define a list (a mutable object) and a tuple (an immutable object). The list includes a tuple, and the tuple includes a list:

>>> my_list = [(1, 1), 2, 3] >>> my_tuple = ([1, 1], 2, 3) >>> type(my_list)  >>> type(my_list[0])  >>> type(my_tuple)  >>> type(my_tuple[0]) 

So far so good. Now, try to think for yourself – what will happen when we try to execute each of the following statements?

(1) >>> my_list[0][0] = 'Changed!'

(2) >>> my_tuple[0][0] = 'Changed!'

In statement (1), what we are trying to do is change my_list's first element, that is, a tuple. Since a tuple is immutable, this attempt is destined to fail:

>>> my_list[0][0] = 'Changed!' Traceback (most recent call last): File "", line 1, in  TypeError: 'tuple' object does not support item assignment

Note that what we were trying to do is not change the list, but rather – change the contents of its first element.

Let's consider statement (2). In this case, we are accessing my_tuple's first element, which happens to be a list, and modify it. Let's further investigate this case and look at the addresses of these elements:

>>> my_tuple = ([1, 1], 2, 3) >>> id(my_tuple) 20551816 >>> type(my_tuple[0])  >>> id(my_tuple[0]) 20446248

When we change my_tuple[0][0], we do not really change my_tuple at all! Indeed, after the change, my_tuple's first element will still be the object whose address in memory is 20446248. We do, however, change the value of that object:

>>> my_tuple[0][0] = 'Changed!' >>> id(my_tuple) 20551816 >>> id(my_tuple[0]) 20446248 >>> my_tuple (['Changed!', 1], 2, 3)

Since we only modified the value of my_tuple[0], which is a mutable list object, this operation was indeed allowed by Python.

Recap

In this post we learned about Python objects. We said that in Python everything is an object, and got to use id and is to deepen our understanding of what's happening under the hood when using Python to create and modify objects.

We also learned the difference between mutable objects, that can be modified after creation, and immutable objects, which cannot.

We saw that when we ask Python to modify an immutable object that is bound to a certain name, we actually create a new object and bind that name to it.

We then learned why dictionary keys have to be immutable in Python.

Understanding how Python "sees" objects is a key to becoming a better Python programmer. I hope this post has helped you on your journey to mastering Python.

Omer Rosenbaum, Swimm’s Chief Technology Officer. Cyber training expert and Founder of Checkpoint Security Academy. Author of Computer Networks (in Hebrew). Visit My YouTube Channel.