Тёмный

Immutable vs Mutable Objects in Python 

Real Python
Подписаться 188 тыс.
Просмотров 63 тыс.
50% 1

dbader.org/python-tricks ► Improve your Python skills, one bite at a time and write Pythonic and beautiful code.
In Python, immutable vs mutable data types and objects types can cause some confusion-and weird bugs. With this video you'll see what the difference between mutable and immutable data types is in Python, and how you can use it to your advantage in your own programs.
You'll also see how to deal with a language quirk in Python that allows objects referenced by immutable types to me modified. Python's definition of "immutable" can be a bit misleading:
Basically, the promise of "immutability" on tuples is only partly true. The tuple itself cannot be modified, but objects referenced by the tuple can be. This is sometimes called "non-transitive immutability."
If the tuple has an immutable field like a string for example, then it cannot be modified. A mutable field like a list however, can be edited, even if it's embedded in the "immutable" tuple.
When the Python documentation refers to an object as being "immutable" they mean the behavior above observed. Other immutable types in Python behave the same way, e.g. namedtuples or frozensets.
If you've ever encountered the following exception and now you want to know why, this is the video for you:
TypeError: 'tuple' object does not support item assignment
* * *
► Python MUGS, T-SHIRTS & MORE: nerdlettering.com
FREE Python Tutorials & News:
» Python Tutorials: dbader.org
» Python News on Twitter: / @dbader_org
» Weekly Tips for Pythonistas: dbader.org/newsletter
» Subscribe to this channel: dbader.org/youtube

Опубликовано:

 

6 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 60   
@michaelkim733
@michaelkim733 4 года назад
wow can i ask what kind of mic you use? the voice is extremely clear
@nasert.988
@nasert.988 3 года назад
Great video. Just one point about modifying a mutable object inside an immutable object. In fact, Python only checks if the objects inside an immutable object are changing or not. If you take id() from your list object (which is inside your tuple), then you see the memory address of your list object. If you modify your list object, the id() or memory address does not change (because this is the property of a mutable object). Since the new list object is not different from the original one, Python does not care and in its opinion still the immutability of the tuple object is not violated.
@nosms6581
@nosms6581 24 дня назад
thanks, this was helpful
@LewisCowles
@LewisCowles 7 лет назад
Surely the non-transitive part benefits runtime performance as python does not have to traverse objects and structures? I actually first noticed Python mutability last year where it stopped me from getting 100% unit tests passing, was a bit of a laughing point when I was done as 5 minutes after I left the interview room I realised what I'd done and made some new rules for the future. On the `cost` side of things in terms of processing speed whilst I'm aware CoW (copy on write) semantics exist in some languages how would you feel about a mnemonic or key-word to make copy or copy on write available to python in a more terse way?)
@TheSRONIX
@TheSRONIX 4 года назад
Thank you! This concept was confusing coming from mainly coding in C.
@soumyarastogi6399
@soumyarastogi6399 3 года назад
Check out my RU-vid channel for more on Python
@zulkifal111
@zulkifal111 5 лет назад
awesome Dan-great clarity-it only gives me a reason to "stalk" { :-)} you on the net-you were crystal clear-im not a programmer by background but dba-ur videos encourages me to take a serious look at python
@realpython
@realpython 5 лет назад
Thanks for the kind words!
@angelsalazar9093
@angelsalazar9093 4 года назад
Thanks, Dan . This was useful
@panjackson4876
@panjackson4876 4 года назад
Very helpful! Thanks!
@mesartwell
@mesartwell 4 года назад
Does anyone know which interpreter is being used? I'm interested in the as-you-type help feature.
@aalapjethwa6452
@aalapjethwa6452 5 лет назад
Very well done...amazing work man
@realpython
@realpython 5 лет назад
Thanks for the kind words!
@mikijasar2594
@mikijasar2594 2 месяца назад
Thanks for your video but I wish you would have done the same for the set because the set does not allow changing mutable elements within the set
@kaveeshashah6267
@kaveeshashah6267 4 года назад
Hi, I have a doubt. We say that the reference to the list doesn't change and hence we can still change the list in a tuple. But why does it stop us in the case of integer? Does the reference change for integers? Sorry I know it sounds stupid bit if you can please clarify it
@LauraBeatris
@LauraBeatris 3 года назад
An integer is an immutable value. Every time that it changes, a new reference in the memory is created.
@saarthakjohari9045
@saarthakjohari9045 6 лет назад
very well explained
@komputer7566
@komputer7566 Год назад
awesome explanation . thank you !
@asthamishra8296
@asthamishra8296 2 года назад
Well explained ..thank you...
@_MANOGNAKONDURUNBKRIST
@_MANOGNAKONDURUNBKRIST Год назад
we are saying numeric data type is immutable but if we assign a=5,we can change 5 to 6 ....but why it's saying immutable
@SmitPatel-hs2hv
@SmitPatel-hs2hv 3 года назад
8:15 Can you please explain "we can modify the objects thats the tuple " holds
@sandy73rocks
@sandy73rocks 3 года назад
If a tuple contains a list as one of its elements, we can modify the list itself which is mutable and that change is visible in the tuple.
@pradishdadhania
@pradishdadhania 4 года назад
Thanks u sir i clear abt topic
@serotonin14
@serotonin14 3 года назад
Thanks a bunch!!😃
@sumande7308
@sumande7308 4 года назад
This helped me a lot as i am coming from java..
@fantom_xop
@fantom_xop 3 года назад
Today this video helped me a lot
@HOWYOUDOIN884
@HOWYOUDOIN884 2 года назад
Why use the word "mutable"? Reminds me too much of muting something, like a television speaker is mutable (you can make it quiet, or change the volume). Why not just use "changeable" and "unchangeable"?
@srappytrex3946
@srappytrex3946 3 года назад
what is this color theme?
@anwermohammad2754
@anwermohammad2754 5 лет назад
very well explained Thank you
@realpython
@realpython 5 лет назад
You're very welcome!
@EpmMaxim
@EpmMaxim 3 года назад
Thank you!!
@satwikshaw1031
@satwikshaw1031 Год назад
Thanks man 🙌
@softwaretestingmentor
@softwaretestingmentor 3 года назад
Crystal clear explanation! I just wonder who are those 11 people who disliked this video :)
@RAHUDAS
@RAHUDAS Год назад
U did not mention numbers are immutable too why?? Or i am missing something to understand??
@muhammadmohsinkhan7354
@muhammadmohsinkhan7354 6 лет назад
thanks man. Good video
@realpython
@realpython 6 лет назад
You're welcome!
@durgapratapbehera8606
@durgapratapbehera8606 4 года назад
Sir can you make a video on how mutability works by using variable assignment
@soumyarastogi6399
@soumyarastogi6399 3 года назад
Check out my RU-vid channel for more on Python tutorials
@MrNagios
@MrNagios 7 лет назад
thanx!
@ahmedelmawrdy4381
@ahmedelmawrdy4381 Год назад
thanks alot
@ukrainiansubarer7767
@ukrainiansubarer7767 3 года назад
It was partly useful to me. Much more interesting part would be to expand with an explanation of memory management by mutable and immutable objects, this would make clear that "non-transistent state".
@NOVAsteamed
@NOVAsteamed 4 года назад
You deserve my sub
@tharmarajashenthan1205
@tharmarajashenthan1205 Год назад
thanks broooo
@ma.jessacarismabalabala9055
@ma.jessacarismabalabala9055 2 года назад
thank you
@lalosalamanca7131
@lalosalamanca7131 2 года назад
Great video
@geoptus
@geoptus 6 лет назад
Hi Dan, thanks for putting on this great tutorial series. I tried out and understood the examples here but found the following oddness. I did: list1 = ['a', 'b', 'c'] list2 = ['d', 'e', 'f'] tup1 = ( 42, list1, 'hello') tup1 >(42, ['a', 'b', 'c'], 'hello') tup1.index(list1) >1 then, tup1[1][1] = 'x' tup1 >(42, ['a', 'x', 'c'], 'hello') tup1.index(list1) >1 list1[1] = 'y' list1 >['a', 'y', 'c'] tup1 >(42, ['a', 'y', 'c'], 'hello) # tup1 item[1] still points to the (mutated) list1 tup1.index(list1) >1 also, tup1[1] is list1 >True - so far, as I expected then, list1 = list2 # not sure if this is now a new assignment or a mutation of list1 list1 is list2 >True list1 >['d', 'e', 'f'] tup1 >(42, ['a', 'y', 'c'], 'hello') # still pointing to the previous contents of list1 tup1[1] is list1 >False tup1.index(list1) >ValueError....etc what is tup1[1] now pointing to? it seens no longer pointing at list1 from where is tup1[1] 'getting' ['a', 'y', 'c'] ? is this list item now simply an indepentent tuple item? This surprised me. I was expecting the pointer/link to persist python 3.6.4
@bissallahekele5320
@bissallahekele5320 3 года назад
Recall tuples are immutable, same way tup1[0] = 40 will throw an error, assigning another list to index 1 will be disallowed. But you can access the list and modify the properties in the list. tup1[1] still points to the object ['a', 'y', 'c'] list1 points to list2's object now
@benc7910
@benc7910 Год назад
Itd be more clear if u could explain with diagrams of memory space and cpu
@narayanpathak221
@narayanpathak221 2 года назад
Awesome 🙌✌️ yeah it's helped
@debjyotichattopadhyay6679
@debjyotichattopadhyay6679 4 года назад
nice work
@realpython
@realpython 4 года назад
Thanks!
@liangyumin9405
@liangyumin9405 5 лет назад
Nice!
@realpython
@realpython 5 лет назад
Thanks!
@studio2038
@studio2038 4 года назад
nice video
@animekanav3950
@animekanav3950 11 месяцев назад
thx
@dhedarkhcustard
@dhedarkhcustard 4 года назад
It's not a bug with python, it's a feature.
@reisaki18
@reisaki18 2 года назад
because list is mutable. is just that simple even you put a list in a tuple, its still a list.
@RayHorn5128088056
@RayHorn5128088056 Год назад
Every immutable object can be easily made mutable and changed then made immutable. Python does not support truly immutable objects that cannot be changed.
@KrishnaManohar8021
@KrishnaManohar8021 4 года назад
object vs instance
@amirafrooze7347
@amirafrooze7347 9 месяцев назад
perfekt
Далее
Python __slots__ and object layout explained
10:16
Просмотров 90 тыс.
I Built 7 EXTREME Rooms in My House!
1:22:07
Просмотров 11 млн
2000000❤️⚽️#shorts #thankyou
00:20
Просмотров 2,3 млн
🛑какие города ждут трек?
00:14
Просмотров 132 тыс.
Cante por mim (Clipe Oficial) - Juliana Domingues
4:38
5 Useful Python Decorators (ft. Carberra)
14:34
Просмотров 84 тыс.
Python Tutorial: Sorting Lists, Tuples, and Objects
12:07
5 More Useful F-String Tricks In Python
9:38
Просмотров 40 тыс.
Python lists, sets, and tuples explained 🍍
15:06
Просмотров 226 тыс.