An exercise to help build the right mental model for Python data.

The “Solution” link visualizes execution and reveals what’s actually happening using 𝗺𝗲𝗺𝗼𝗿𝘆_𝗴𝗿𝗮𝗽𝗵: https://github.com/bterwijn/memory_graph

  • Oka@sopuli.xyz
    link
    fedilink
    arrow-up
    4
    ·
    17 hours ago

    I expect A if “b” is a clone, or E if it’s a reference. But I also wouldnt combine array operations like this.

    The answer being C feels like a bug.

    • Successful_Try543@feddit.org
      link
      fedilink
      arrow-up
      3
      ·
      3 hours ago

      In my limited understanding, the 5th step b = b + [4] would cause problems, infinite execution or alike, if it kept being a reference.

      Coming from MATLAB, anything but A feels like a bug. I don’t want my script to use references when initializing a variable unless I tell it to.

    • tomenzgg@midwest.social
      link
      fedilink
      English
      arrow-up
      2
      ·
      15 hours ago

      Eh, I get it. The equal operator creates a reference but the plus operator isn’t destructive so it creates a new list and overwrites the variable b with a new list, when assigned.

      Of course, this would all be avoided if creating copies was the norm; which is why I stick with functional languages.

      • bterwijn@programming.devOP
        link
        fedilink
        arrow-up
        2
        ·
        11 hours ago

        Copying a list with a million elements every time you make a small change is not fun. Sure, you can optimize a bit behind the scenes, but that still gives a lot of overhead.

        • tomenzgg@midwest.social
          link
          fedilink
          English
          arrow-up
          1
          ·
          8 hours ago

          And we can create data structures and algorithms that fit a more functional style without relying on imperative assumptions of how data should be handled. Data structures like vlists could be applicable, for example.