8 ms·
Huh I never even thought we would need to create copy of an object when adding new item to it (like a new item to list for example). Is there any drawback on do
by pokepim 5y ago
Huh I never even thought we would need to create copy of an object when adding new item to it (like a new item to list for example). Is there any drawback on doing that in standard pythonic way? I actually learned to program using Python and it was my first language. Since then I only used JS. In both I like using functions a lot and rarely dabble in OOP since it is more conveniet to me.
- tyingq 5y agoYou can control the behavior manually, like: first = [0,1,2] second = [*a,3] # first is unchanged, second = [0,1,2,3] Or second=itertools.chain(first, [3]), which avoids the copy. Though, to me, it's asking for trouble later.
- deleted 5y ago[deleted]
- sgeisenh 5y agoYou often lose performance in traditional imperative languages when aiming for persistence. When you have immutability guarantees (like in many functional programming languages like ML or Haskell) you can avoid making copies by sharing the parts of the data structure that don't change. If this kind of thing interests you, you should check out Chris Okasaki's book "Purely Functional Data Structures".
- eximius 5y ago"avoid making copies" dors not always equal "performance". Depending on your access patterns, having the data colocated can be more important. But immutability sure is nice when you can have it.
- tusharsadhwani 5y agowhether mutating data is better than creating a new copy for everything is a really long debate about immutability and functional programming, with good points on either sides, but that's really beyond the point here. In my opinion, you should use whichever method makes your code easy to read and understand for your usecase.