Python's sharpest corner is ... plus equals? (+=)

แชร์
ฝัง
  • เผยแพร่เมื่อ 3 ก.ค. 2024
  • If you thought x+=y means x=x+y you'd be wrong!
    Python's plus equals augmented assignment syntax is more complex than many people realize. Let's take a look.
    (Sorry for the dark purple again! I've changed it in my ide to pink for the future!)
    ― mCoding with James Murphy (mcoding.io)
    Source code: github.com/mCodingLLC/VideosS...
    Docs for iadd: docs.python.org/3/reference/d...
    SUPPORT ME ⭐
    ---------------------------------------------------
    Patreon: / mcoding
    Paypal: www.paypal.com/donate/?hosted...
    Other donations: mcoding.io/donate
    BE ACTIVE IN MY COMMUNITY 😄
    ---------------------------------------------------
    Discord: / discord
    Github: github.com/mCodingLLC/
    Reddit: / mcoding
    Facebook: / james.mcoding
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 560

  • @ArsenicDrone
    @ArsenicDrone 2 ปีที่แล้ว +177

    More broadly, the choice in Python not to have a prominent division between things that are pointers (still can be changed when you send them off somewhere else) and things that are not pointers (are copies when they're elsewhere) is a very easy place to get tripped up, especially for those who are used to stricter languages.

    • @tongpoo8985
      @tongpoo8985 ปีที่แล้ว +21

      Definitely my least favorite thing about python

    • @JohnChaussard
      @JohnChaussard ปีที่แล้ว +3

      i believe everything is a pointer in python, and nothing acts like a copy, making it more easy to understand the behavior of a program… In the last example given, L was indeed a pointer, but the += reassigned the value of the pointer to a new place, and therefore, the change couldn’t be seen from the main function… The problem comes from the fact that, if not well documented, it is difficult to know what will be the behavior of basic functions (addition, +=, …) on objects.

    • @daskadse769
      @daskadse769 ปีที่แล้ว +17

      @@JohnChaussard While yes, everything in python is an object (and thus, a pointer), the immutability of some things make them behave more like values. But as you are saying, when specific operations are ambiguous over whether they operate on the pointer or the object, that's confusing at best (and bad language design at worst). This is all over python (see descriptors for example), and while it does enable some dark magic, I'd personally argue it does not make the language more usable.

  • @blakewalsh9489
    @blakewalsh9489 3 ปีที่แล้ว +648

    I don't feel bad for having a severe distrust of += in python now, nice to have a clearer understanding of it though.

    • @deidyomega
      @deidyomega 3 ปีที่แล้ว +27

      += is fine, just always treat everything like a primitive and you'll be safe. In his example, if he would have returned the l var ([4,5,6]), he would have gotten the expected results.

    • @devanshgarg31
      @devanshgarg31 2 ปีที่แล้ว +1

      Yess

    • @insidiousmaximus
      @insidiousmaximus 2 ปีที่แล้ว +28

      @@SquidBeats there is no spoon

    • @aleongh
      @aleongh 2 ปีที่แล้ว +2

      @@SquidBeats k

    • @DendrocnideMoroides
      @DendrocnideMoroides 2 ปีที่แล้ว +5

      @@SquidBeats how do you know that Hell is real? have you seen it, if so how can I see it?

  • @Mutual_Information
    @Mutual_Information 3 ปีที่แล้ว +374

    I’ve been writing Python code for a long time.. and a lot for my own videos, but I learn something new with each of these lessons! I think I need to hunker down and make sure I watch all of them.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +39

      Thanks for the support !

    • @doltramir
      @doltramir 3 ปีที่แล้ว +10

      Same here. I'm writing python for around 7 or 8 years now. And this is the first time i saw this problem. This is because i never used python in a way that will show this behaviour (because tuple is strictly immutable, and because i use list.append and list.extend instead of adding it). But i immediately got what will happen in this code. Just didn't happen to me ever.

    • @SquidBeats
      @SquidBeats 2 ปีที่แล้ว

      Jesus Christ is God and is the only way. Hell is real whether you believe it or not.

  • @pharoah327
    @pharoah327 ปีที่แล้ว +14

    There's a principal in language design known as "least astonishment". The idea is to make a feature work in the least astonishing (aka least unexpected) way. So when you create a feature, make it work in the way most developers would expect it to work. I don't think Python got the memo on this

  • @MitchellD249
    @MitchellD249 3 ปีที่แล้ว +446

    "Slap that like button an odd number of times"
    *slaps like, then dislike, then like 2 more times*
    What now mCoding?

    • @mCoding
      @mCoding  3 ปีที่แล้ว +197

      You got me.

    • @Pacvalham
      @Pacvalham 3 ปีที่แล้ว +28

      How about "toggle the like button an odd number of times"?

    • @tahaan99
      @tahaan99 3 ปีที่แล้ว +12

      @@Pacvalham But that wouls still not have the desireable effect if the person has followed the instructions an odd number of times before.

    • @mrpedrobraga
      @mrpedrobraga 3 ปีที่แล้ว +16

      @@mCoding
      while ( not like_button.is_activated() ):
      toggle_like_or_dislike()
      Runtime dynamic check.

    • @relvisdsouza3541
      @relvisdsouza3541 3 ปีที่แล้ว +2

      @@mrpedrobraga you went full nerd

  • @usharma1624
    @usharma1624 3 ปีที่แล้ว +749

    Developer1: "+= has a bug, what should we do?"
    Developer2: "Just fix it"
    Developer1: "We don't have time, we must do something else"
    Developer2: "Tell everyone that this is a feature, not a bug"
    Developer1: "... Great Idea"
    Great video! Learnt a lot form this!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +88

      Exactly!

    • @vbregier
      @vbregier 3 ปีที่แล้ว +45

      I would say this is broken semantics, more than a bug.
      An operator should not have two very distinct semantics (either modify the object binded to the variable, or rebind the variable to a new object).
      There should be two distinct operators / functions, for each semantic.

    • @adrulb
      @adrulb 3 ปีที่แล้ว +15

      @@vbregier I wouldn't say it's broken, it's just different contexts: in all cases it means "add this to that", if I said I wanted to "add a character to a string" it's obvious what my intention is: take the string, append the character to the end and wríte that back to the variable. If I said I wanted to "add a number to a number" it's also obvious what I want to do. Same goes for "adding a string to a list (of strings)".

    • @vbregier
      @vbregier 3 ปีที่แล้ว +32

      @@adrulb The semantics of an operator should not depend on the context.
      Different semantics need different operators / methods.
      You are not seeing it because the word "add" itself has this problem : do you mean generate a new value, or modify the value you add to ?
      Mutability of objects is crucial in programming, it must be clear which objects are modified and which are not for a given operation.

    • @dtkedtyjrtyj
      @dtkedtyjrtyj 3 ปีที่แล้ว +23

      @@vbregier Yes, the problem is that concatenation is not the same as addition. Not having a separate concatenation operator is one of the few flaws in Python.

  • @aragonnetje
    @aragonnetje 2 ปีที่แล้ว +26

    Personally the "BadList" implementation makes more sense to me. For appending things to a list, we have append and extend. a += b should be effectively the same as a = a + b

    • @mintypotato6205
      @mintypotato6205 ปีที่แล้ว +5

      in python 2, this was the implementation, and if you iteratively created a large list, it would use SEVERAL GBs of memory (think 125GB for a 500 000 element (500 KB+) list).
      My friend came across this when doing a file handling program and crashed python - It can be done in less than 10 lines of code (and it is difficult to fix).

    • @aragonnetje
      @aragonnetje ปีที่แล้ว +2

      @@mintypotato6205 wouldn't it be instantly fixable with .extend() though?

    • @Redhotsmasher
      @Redhotsmasher ปีที่แล้ว

      @@mintypotato6205 Difficult to fix how? Did Python 2 lists not have the .append() method or something?

  • @ManuelBTC21
    @ManuelBTC21 3 ปีที่แล้ว +42

    7:30 Rarely comes up indeed. Can't recall ever encountering this specific issue after 10+ years of programming in Python. In any case, mutability is the root cause of this and should be handled with care.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +7

      It has only come up once in my programming career!

  • @VojtechMach
    @VojtechMach 3 ปีที่แล้ว +86

    Man, you are great, this is exactly the content I was missing on YT. Advanced stuff, straight to the point. Keep up the good job.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +4

      Thank you for the kind words!

  • @Ovicron
    @Ovicron 3 ปีที่แล้ว +112

    I didn't even know about the __iadd__ method 😅.
    Also, The audio is so good now.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +18

      Thank you so much, I'm doing everything I can to up the audio quality

    • @Sirjosephcharles
      @Sirjosephcharles 3 ปีที่แล้ว +1

      iAdd is part of @mCoding user created class. This doesn’t mean it’s native method, correct?

    • @Ovicron
      @Ovicron 3 ปีที่แล้ว +9

      @@Sirjosephcharles the dunder iadd method is a magic method, it is used to overload the += operator.

  • @HaBBiSiFy
    @HaBBiSiFy 2 ปีที่แล้ว +4

    Great topic. I had a hard time figuring this out a year ago when I was working with PyTorch - it turned out it was imperative to use x = x + foo instead of x += foo in many places since they are, counterintuitively, not the same expression... This video shed some light to the matter. Thank you!

  • @dsenese
    @dsenese 3 ปีที่แล้ว +41

    The mutable integer id really blow my mind! I learn so much with your videos. One suggestion: you could put the python docs that you are refering to on the description :) Thanks!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +7

      docs.python.org/3/reference/datamodel.html#object.__iadd__

    • @lawrencedoliveiro9104
      @lawrencedoliveiro9104 3 ปีที่แล้ว +8

      Unfortunately, TH-cam screws up the formatting of that URL ...

  • @Treebark1313
    @Treebark1313 3 ปีที่แล้ว +4

    This video is fantastic. I've been using Python for years and noticed some weirdness with these operators but never dug into it. Thanks for producing such high quality educational content!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      You're very welcome!

  • @griof
    @griof 3 ปีที่แล้ว +14

    Another sharp corner: function default mutable parameters. I think most of us have fallen in this bug... I mean this _feature_

  • @franferri
    @franferri 3 ปีที่แล้ว

    You are one of the best perk teachers around the youtube block. Enjoying your vids a lot.

    • @mCoding
      @mCoding  2 ปีที่แล้ว

      Thank for the praise!

  • @davidharmeyer3093
    @davidharmeyer3093 2 ปีที่แล้ว +9

    Just watched the entire video and honestly, I still feel like it's even more surprising that ++ doesn't exist

  • @AndyChamberlainMusic
    @AndyChamberlainMusic 3 ปีที่แล้ว +50

    "as always, slap that like button an odd number of times"
    me, an intellectual: watches the video an even number of times

    • @mCoding
      @mCoding  3 ปีที่แล้ว +11

      >:(

  • @brightsideofmaths
    @brightsideofmaths 3 ปีที่แล้ว

    Very nice channel! Keep up the good work!

  • @AbelShields
    @AbelShields 3 ปีที่แล้ว +10

    Ahh Python, reminds me of good old True = False, and messing around with the cached small integer objects, changing their actual ctypes value. It's definitely good for quick prototyping but there are so many quirks... Looking forward to watching more!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +4

      Good times!

    • @lawrencedoliveiro9104
      @lawrencedoliveiro9104 3 ปีที่แล้ว +5

      Seems “True” and “False” could indeed be (re)assigned in Python 2, but they are reserved words in Python 3. Not before time ...

  • @infinitelyexplosive4131
    @infinitelyexplosive4131 3 ปีที่แล้ว +1

    You're very good at presenting technical topics.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      It's a gift!

  • @MrRocksW
    @MrRocksW 3 ปีที่แล้ว

    Your channel is great really enjoying your videos. I like watching intermediate/ advanced videos on python.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Glad you like them!

  • @vsolyomi
    @vsolyomi 3 ปีที่แล้ว +87

    A talk on persistent data structures would be awesome... You don't seem that much a functional programming enthusiast, but I think it might be great to discuss limitations of standard data types in relation to copying and mutability and how it can be circumvented.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +39

      Python supports many program paradigms, including functional. This would be a great idea for future!

    • @ross825
      @ross825 2 ปีที่แล้ว +3

      I've been playing with pyrsistent and I have fallen in love with using evolvers instead of mutable mappings and arrays.

  • @tudor1899
    @tudor1899 หลายเดือนก่อน

    Always top notch stuff from you.

  • @Tal__Shachar
    @Tal__Shachar 3 ปีที่แล้ว +28

    Dude. Do you sleep?
    Your content is of impeccable quality and is just shooting into my notif box. How do you make so many freaking good videos I love your channel ahhh

    • @mCoding
      @mCoding  3 ปีที่แล้ว +9

      The bags under my eyes you might think that I don't ever sleep! But rest assured, I get plenty! Thank you for the support

  • @andersonklein3587
    @andersonklein3587 2 ปีที่แล้ว +5

    The more I learn about other languages, the more I understand why people still write in C. It's the only language to date where things never not made sense to me.
    You pass references, pointers, you can modify any piece of memory anywhere in the stack, or allocate heap, it's perfectly transparent. When working with Python, that I do often use and is great for some stuff, whenever I'm working with a new function or circumstance I never know what to expect without reading the full documentation on how it works under the hood.

    • @jurjenbos228
      @jurjenbos228 ปีที่แล้ว +1

      You know what they say: C combines the power of assembly language with the flexibility of assembly language.

  • @microwavecoffee
    @microwavecoffee 3 ปีที่แล้ว +3

    These videos are great. Hope your channel gets big.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      I hope so too! Thanks for your support!

  • @ahuddleofpenguins4842
    @ahuddleofpenguins4842 2 ปีที่แล้ว

    Never even touched code before. Thanks for the vid!

  • @shreydixit2690
    @shreydixit2690 3 ปีที่แล้ว +11

    Another great video! Keep it Up

    • @mCoding
      @mCoding  3 ปีที่แล้ว +7

      Thanks! Will do!

  • @rosiefay7283
    @rosiefay7283 3 ปีที่แล้ว +9

    2:38 Argh. This is the sort of bug you can get when you use C macros which have parameters. And yet you get bugs like that in python even if you write something which looks safe.

  • @CrapE_DM
    @CrapE_DM 3 ปีที่แล้ว +11

    Yeah, the data model for __iadd__ is broken in my opinion. Instead of usually returning `self`, it shouldn't return anything. Then, instead of the += turning into `x = x.__iadd__(y)`, it should just be `x.__iadd__(y)`. The whole point of the in-place overloads is to modify yourself instead of returning a new object, as the base versions of the operators do. Not only would this help people understand the point better, it would remove your tuple bug.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +3

      yeah this really confused me at first. I think the part that got me was the reassigning the variable after doing the iadd, which other languages typically don't

  • @user-jb7no2kv8f
    @user-jb7no2kv8f 2 ปีที่แล้ว

    The best plus equal explanation I have ever saw on yb

  • @Insomn3s
    @Insomn3s 3 ปีที่แล้ว

    Great job! Thank you for your videos!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Glad you like them!

  • @cynical5062
    @cynical5062 ปีที่แล้ว +1

    3:27 "I can't change a 1 into a 2"
    this is mostly true, but with ctypes:
    import ctypes
    ctypes.c_longlong.from_address(id(1)+24).value = 2
    print(1)
    this code prints 2
    until you change the value again, or restart python, 1 is 2

  • @monkeecrap
    @monkeecrap 3 ปีที่แล้ว +1

    Another great video! Love learning these detailed but important nuances of Python.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      More to come!

  • @robertbrummayer4908
    @robertbrummayer4908 3 ปีที่แล้ว

    Great job!

  • @cebtibia
    @cebtibia 3 ปีที่แล้ว +4

    Amazing content! Keep the great work!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Appreciate it!

  • @liammail9884
    @liammail9884 3 ปีที่แล้ว +1

    Pretty sure I just watched an 8-min Jedi mind trick designed to increase James' subscription count. Fair enough. Subscribed because it helps James and it feels good.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      I appreciate it!

  • @nicko1227
    @nicko1227 3 ปีที่แล้ว +1

    This channel is a rare treasure of useful secrets we never knew. Thanks for the great content. Looking forward to more of useful videos.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Thanks for watching!

  • @aronhegedus
    @aronhegedus 2 ปีที่แล้ว +2

    interesting to see what COULD go wrong. I think the lesson is: don't write a class that inherits from list, and keep += for basic loops, and use .extend() for lists instead

  • @amikomalania3406
    @amikomalania3406 3 ปีที่แล้ว +7

    "that can get you into a lot of trouble if you're not familiar how python works" ... and that's why it's not a feature rather a bug(to me).
    That was one of the first serious case that had my and Python's relationship in trouble. "Fluent Python" also demonstrates this type of example and it had my mind blown away. You cannot just report an error on something and then do that exact thing anyways.
    Other than that, great video! I don't think i've seen this "bug" covered elsewhere. It'd be cool if you covered data-model more in depth. Thanks!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Well, feature or bug, it's not that big a deal once you understand!

  • @justinfuruness7954
    @justinfuruness7954 3 ปีที่แล้ว +2

    Saw this in a pycon video the other day. Super interesting!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      Oh no! someone else covered it first!

  • @Soljarag5
    @Soljarag5 3 ปีที่แล้ว

    Super interesting information!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Glad it was helpful!

  • @hannesthiersen8170
    @hannesthiersen8170 2 ปีที่แล้ว +5

    I honestly didn't know the += operator can be used on anything other than arithmetic data types in python. However, is it really more convenient and clear compared to the append and extend methods for lists for the sake of argument? Nevertheless it's good of you to point this out. Thanks.

    • @mdcoulson
      @mdcoulson ปีที่แล้ว

      You can use any operator on any object as long as the method called by the operator is defined for the object. This is just the fundamental concept embraced by the object-oriented programming paradigm.
      Create a new class with the __getitem__() dunder method defined and suddenly you can use the indexing operator on any object instantiated by your new class, and it will execute whatever you defined it to execute, regardless of whether it has anything to do with indexing at all.
      Most of these "gotcha"-level videos revealing new information have less to do with actually introducing new information and more to do with just exposing our laziness in applying already understood knowledge. We all know operations in Python are in-place or not, so understanding whether the augmented operators are in-place operators is just a consequence of whether we bothered to read the documentation regarding them.

  • @Cucuska2
    @Cucuska2 3 ปีที่แล้ว

    Whoah, this was such a cool video!

  • @egehurturk6209
    @egehurturk6209 3 ปีที่แล้ว

    This channel is literally on fire

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Woo!

  • @brawldude2656
    @brawldude2656 2 ปีที่แล้ว

    Now I'm going to use "+=" with try except block when i want to assign a tuple member.
    Thank you mCoding now i know how to use this "feature".

  • @lepsycho3691
    @lepsycho3691 3 ปีที่แล้ว +2

    When I first started coding in python coming from c++, I was baffled by the fact that there was no '++' to augment an integer and that I had to use the '+='. How naive I was back then! But even though I understand now that the pythonic way of doing things, rarely if ever need an index for a loop, I did not understand the specific reason why It is that way.
    Thank you for this amazing explanation!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +2

      Indeed! I pretty much never plus equals for integers.

    • @Starwort
      @Starwort 3 ปีที่แล้ว +2

      @@mCoding you should always use += where it makes sense (note that for lists etc. they have an extend method which is usually better) as it allows the implementation to optimise the operator, which is also the reason for the behaviour explained here. += is always the right choice, except when there's an appropriate method

  • @Zoltag00
    @Zoltag00 3 ปีที่แล้ว +3

    I would be interested in hearing your views about Pythons behaviour when returning from a finally block (how it implicitly discards any unhandled exceptions prior to the finally block)

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      That would be a good video topic. Generally, you probably don't want to do things that pep8 unconditionally discourages :)

  • @GabrielsEpicLifeofGoals
    @GabrielsEpicLifeofGoals 3 ปีที่แล้ว +4

    "It's not a bug it's a feature. *wink wink*
    But sir, whould we-
    *points gun* I SAID ITS A FEATURE WIN WINK

  • @rizerphe
    @rizerphe 3 ปีที่แล้ว +45

    Now I have even more reasons to learn functional programming

    • @casperes0912
      @casperes0912 3 ปีที่แล้ว +10

      And I have even more reason to hate Python! :D

    • @mCoding
      @mCoding  3 ปีที่แล้ว +17

      All languages have their ups and downs!

    • @johannestafelmaier616
      @johannestafelmaier616 3 ปีที่แล้ว +3

      luckily, Python has a few very neat features that allow for pure functional programs, like lambda, yield and defs inside defs... :)
      can't image programming without those nowadays

    • @welltypedwitch
      @welltypedwitch 3 ปีที่แล้ว +1

      @@johannestafelmaier616 Wait, what does yield have to do with pure fp?

    • @casperes0912
      @casperes0912 3 ปีที่แล้ว +2

      @@mCoding no doubt. Python and I don’t get along well though I have to use it for some parts of my work. I can see why some people really like it and I do acknowledge its strengths. But it’s just really not my preference to work with. I jokingly tell my colleagues I’d rather write pure assembly but it’s all tongue and cheek and I respect Guido and his work with python as well as everyone else involved and of course everyone who’s good at programming in python. It’s just preference and my preference is elsewhere.

  • @nO_d3N1AL
    @nO_d3N1AL 2 ปีที่แล้ว +2

    3:40 Interesting that the id is different every time. I presume it is derived from the memory location, similar to the default hashCode implementation in Java?

  • @MrSteini124
    @MrSteini124 3 ปีที่แล้ว

    Love your content!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      I appreciate that!

  • @auto_ego
    @auto_ego 3 ปีที่แล้ว

    Please keep making content like this.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      Will do!

  • @yiannifunataoldotcom
    @yiannifunataoldotcom 3 ปีที่แล้ว

    I really really like your videos!!!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Thanks for your support!

  • @Achrononmaster
    @Achrononmaster 3 ปีที่แล้ว +3

    "Make sure the thumbs up has changed color once and only once before you leave." Anyone got a problem with that?

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      What about colorblind people?

  • @Speglritz
    @Speglritz 3 ปีที่แล้ว

    If you use an integer which is sufficiently maybe the reference will not change. From my own experiements I've seen that python shares reference for small numbers, presumably because they are used very often and will be a benefit to performance.

  • @fejfo6559
    @fejfo6559 3 ปีที่แล้ว +3

    here I was thinking a+=b was just syntax sugar for a = a+b

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Not a bad assumption! This is what it means in some languages for primitive types!

  • @marco.nascimento
    @marco.nascimento 2 ปีที่แล้ว

    Quite interesting, nice video :)

    • @mCoding
      @mCoding  2 ปีที่แล้ว

      Thanks, glad you enjoyed!

  • @gambiando
    @gambiando 3 ปีที่แล้ว

    Wow I was running into a "bug" because of this feature and didn't know this was the cause. Thank you and thank TH-cam recommendation for popping this out on my feed.

  • @benjamindonnot3902
    @benjamindonnot3902 3 ปีที่แล้ว

    I didn't knew that. Thanks! 😊

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      You bet!

  • @RoiEXLab
    @RoiEXLab 3 ปีที่แล้ว +6

    I already kinda knew this inconsistency because coming from other languages you'd expect
    x += y
    to be short hand for
    x = x + y
    Which as you explained isn't true for lists.
    If it were just a short hand expression it would completely avoid this Problem and python could just add another operator for in-place addition to make up for the missing functionality.
    But yeah, nice video and i learned something new

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      Thanks!

  • @MauriceWilliams
    @MauriceWilliams 3 ปีที่แล้ว

    Bro, why did you cook my brain like that? I only understood about 20% of what you were saying.

  • @WashingtonFernandes
    @WashingtonFernandes 3 ปีที่แล้ว

    great vid!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      Thank you so much!

  • @angello9203
    @angello9203 ปีที่แล้ว

    I've almost never used it, only for increasing numerical variables, but the documentation that I check out when learning always had alternative methods that it's suggested to use

  • @dewaard3301
    @dewaard3301 ปีที่แล้ว

    This is the kind of unexpected behavior that will have you stuck on a bug for days.

  • @dominiator_
    @dominiator_ ปีที่แล้ว

    this blew my mind

  • @1234567qwerification
    @1234567qwerification ปีที่แล้ว

    Another sharp corner only slightly touched here is that .append() would do flawlessly on a list item in a tuple, because it preserves the constant pointer.

  • @supercellodude
    @supercellodude ปีที่แล้ว

    Operator overloading is quite tricky for maintaining clarity and correctness whether it's C++, Python, Haskell ...
    I think the nature of overloading "hiding" function calls is what partly inspired the Zig language from the perspective of C++

  • @raghuvanshmani8185
    @raghuvanshmani8185 3 ปีที่แล้ว

    How great it is to MASTER BASICS at this lvl. !!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      A strong foundation is incredibly important!

  • @MidnightSt
    @MidnightSt ปีที่แล้ว

    this confirms my intuitive assumption that every sensible language implements "+=" just as a syntactic sugar for "var = var + value"

  • @michaeledwardharris
    @michaeledwardharris ปีที่แล้ว

    Fascinating, once again. You are an excellent teacher. I think the += behavior in python is highly questionable lol.

  • @aryanparekh9314
    @aryanparekh9314 3 ปีที่แล้ว +17

    Here before this channel blows up!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +4

      Thank you so much for your support!

  • @youuuuuuuuuuutube
    @youuuuuuuuuuutube 2 ปีที่แล้ว

    - Something is broken, can you fix the bug?
    Python programmer: it's not a bug, it's a feature!

  • @arc6552
    @arc6552 3 ปีที่แล้ว

    Finally, someone using +=

  • @georgeskhater487
    @georgeskhater487 3 ปีที่แล้ว +7

    Let's stick to .append shall we. Btw is there a difference between += or .append for a list?

    • @NateROCKS112
      @NateROCKS112 3 ปีที่แล้ว

      Yes, because += acts like extend, not append. Otherwise, not to my knowledge.

    • @georgeskhater487
      @georgeskhater487 3 ปีที่แล้ว +1

      @@NateROCKS112 oh okay thanks I didn't even know += was a thing for lists tbh I just assumed

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Append, extend, it's all the same for one element!

    • @simonconrad4402
      @simonconrad4402 3 ปีที่แล้ว

      @@georgeskhater487 += is cooler because you can use it in one liners :P

    • @Starwort
      @Starwort 3 ปีที่แล้ว

      @@simonconrad4402 ...extend can be used everywhere += can and more?

  • @chaosopher23
    @chaosopher23 2 ปีที่แล้ว

    I have always been suspect of shorthand expressions. x = x + 1 is how I learned when BASIC had line numbers, C/C++ came along and made me hang a semicolon at the end of it, and Python circumcised it off for me again. x = x + 1 is more readable.

  • @felipedezotti5879
    @felipedezotti5879 3 ปีที่แล้ว

    Incredible! Always read that tuples were immutable and they are, but no so much

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      The rabbit hole goes even deeper than I mentioned in this video…

  • @realansgar
    @realansgar 3 ปีที่แล้ว +1

    So how should a custom class implement __iadd__ to not change the object itself? In other words, how should BadList be changed to behave like list, where __iadd__ works regardless of scope.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      iadd is supposed to modify self (e.g use self.extend(other)) and return self if possible! This is already what the builtin list does, thankfully

  • @john.dough.
    @john.dough. 3 ปีที่แล้ว

    This is so good.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Thanks!

  • @lucaspacheco1081
    @lucaspacheco1081 3 ปีที่แล้ว

    These videos are great even for experienced coders, great work!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Glad to hear that!

  • @gregorymorse8423
    @gregorymorse8423 3 ปีที่แล้ว +3

    Immutable integer types seems ridiculously inefficient, I've never understood such design decision. Ideally mutable and immutable types are available and the programmer chooses the appropriate one. In cryptography code with lots of math on big integers for example, mutable variants are far better performing unless you need a copy returned and then you want immutable. Why cant we have the best of both at our disposal.

    • @zapazap
      @zapazap 3 ปีที่แล้ว

      numpy.

  • @user-md7yv4mw7e
    @user-md7yv4mw7e 3 ปีที่แล้ว +3

    Vietnam/C++ copy move constructor flashbacks from this video)
    Really nice knowledge about python

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      Haha, we've all been there!

  • @TechSY730
    @TechSY730 ปีที่แล้ว

    With the benefit of bindsight, there probably should have been two different dunder methods.
    * One for when the return should be reassigned to the left side of the +=
    * That returns nothing (except for possibly NotImplemented). The change would be expected to happen to the first parameter (usually 'self')
    That way, when trying to do += on members or elements, Python would know whether to do the final reassignment based on which is present (or which one doesn't return NotImplemented).
    Of course this raises the issue of what to do if both are present, or which order they should be attempted in. So it would be a new sharp corner about _implementing_ +=
    But that moves the sharp corner to the implementer, not the user of the API. But that still would have been a worthwhile improvement.

  • @liang3163
    @liang3163 3 ปีที่แล้ว +1

    To summarize, for mutable variable m1, "+=" will create a new mutable variable m2, and then copy the content of m1 into m2.
    Just remember "+=" will always create a new object and that's it

    • @liang3163
      @liang3163 3 ปีที่แล้ว

      Sorry, just ignore this comment, what I sad is wrong.

  • @quack3891
    @quack3891 3 ปีที่แล้ว +1

    Me: *doesn't use python at all since I use C++ on more occasions*
    also Me: "ooh new video from mCoding about python? time to drop my projects and watch"

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      I appreciate it so much!

  • @error1number404
    @error1number404 3 ปีที่แล้ว

    if i not wrong, numbers from 0 to 255 has preset id and it is one of the reason of changing id there 3:30

  • @dtkedtyjrtyj
    @dtkedtyjrtyj 3 ปีที่แล้ว +1

    I found all of these example completely obvious, natural and well... correct.
    It's not even weird, how _else_ would they work?
    ...I may have used Python extensively during my formative years.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      I should make a duplicate video of += in C++ and that will scar you!

    • @dtkedtyjrtyj
      @dtkedtyjrtyj 3 ปีที่แล้ว

      @@mCoding I developed php for eight years, C++ doesn't scare me.

  • @neiliusflavius
    @neiliusflavius 2 ปีที่แล้ว +1

    It feels as if they would have been better off not adding these operators to the language. They mean something clear in other languages but that doesn't fit well with the data model of Python so it would have been clearer to force the one extra keystroke of x=x+1 instead of x+=1.

  • @paxdriver
    @paxdriver 3 ปีที่แล้ว

    Great channel! New sub. Thanks much, can't wait to binge your videos all weekend 😊👍

  • @jenselstner5527
    @jenselstner5527 3 ปีที่แล้ว +1

    Use C: Make it complicated. Use Python: Add complexity.
    Even I do not use Python to program with, it's enlightened to see it's pitfalls.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Pitfalls, or necessary consequences? Sometimes it's hard to tell!

    • @jenselstner5527
      @jenselstner5527 3 ปีที่แล้ว +1

      @@mCoding I see them as pitfalls, because it breaks intuition.

  • @12345origamimaster
    @12345origamimaster 3 ปีที่แล้ว +3

    Ive had a bad experience with this in a sorting simulator... best way i had was to return the lists from the functions

    • @mCoding
      @mCoding  3 ปีที่แล้ว +3

      Yeah, it kind of forces you to use temporaries

  • @oleksiihurov
    @oleksiihurov 3 ปีที่แล้ว

    Will there be more weirdness for hashable types (additional step in whole assignment procedure) where the += operator defined?

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      I don't think the hash will come into play, perhaps someone else has a counterexample?

  • @equenos
    @equenos ปีที่แล้ว

    This thing almost made me loose my sanity when I tried to implement it in one of my projects. Basically I wanted to make a dummy class that would do nothing on __iadd__ except memorising that __iadd__ was called. And due to other implementation details this __iadd__ ended up setting weird attribute values to other seemingly unrelated objects. It took me a while to figure out the reason

  • @Aditya-ne4lk
    @Aditya-ne4lk 3 ปีที่แล้ว +3

    How do you come across these quirks?

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      I push every language to its limits and get burned!

  • @adamsmith7630
    @adamsmith7630 3 ปีที่แล้ว

    Reminds me of the mutable default argument "gotcha." def frobnicate(foo=[]): foo.append(1); return foo; has surprising behavior when you run with the default argument more than once.

    • @joseville
      @joseville 3 ปีที่แล้ว

      Yeah, that was surprising.
      You just keep attending to the same list.
      best to handle that I know this is
      def foo(l=None):
      l = l or []
      ...

  • @Lo323984
    @Lo323984 3 ปีที่แล้ว +1

    Does this also apply to the non in-place += operator? I.e. x = x + 1. I assume not, since iadd is not called there.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +3

      Actually, x=x+1 does something completely different! Furthermore, a raw plus operation is expected to make a copy, not modify the original, and also, a raw equals sign is expected to rebind the variable.

  • @michaelcorbett4236
    @michaelcorbett4236 3 ปีที่แล้ว +3

    Python is built on C. Arrays always have the first element as the pointer, so as you increase the list size the memory address stays the same. Integers don't tend to do this in C. The value is either written into a new memory location or it uses an enumerated one.

    • @zokalyx
      @zokalyx 2 ปีที่แล้ว +1

      CPython is built on C. Python itself is an abstract language, with no pointers or adresses.

  • @rexygama7697
    @rexygama7697 3 ปีที่แล้ว

    "Slap that like button an odd number of times!"
    I like that lol

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Ty Ty!

  • @castelan3419
    @castelan3419 3 ปีที่แล้ว +3

    Nice video

  • @ophotovideo
    @ophotovideo 2 ปีที่แล้ว

    I did learn that, almost 30 years ago, but it was on C++