-3

My confusion arises from the question - Difference between [[0]*m]*n and [[0 for i in range(0,m)] for j in range(0,n)]

There it says that integers are not referenced because they are cheap but since lists are expensive to copy, but how is it decided what to copy and what not to, should I be worried about similar behaviour for strings in any case or for any other objects in case I decide to do something like

[<object>]*m
  • 2
    This "explanation" at the end of the answer is completely wrong and makes no sense. The only reason why you don't get into problems in this case is that you can't mutate an int, so the only thing you can do to an int that is an item of a list is replace it by another object. Problems occur when the list items are lists and you mutate (not replace) some of these lists. – Thierry Lathuille Jun 04 '22 at 17:01
  • 1
    That answer is incorrect. Python is not C, and has no "copy-by-reference"/"copy-by-value" distinction. The behavior asked about in that question is due to lists being mutable and integers being immutable. – CrazyChucky Jun 04 '22 at 17:02
  • 4
    I highly recommend this read: https://nedbatchelder.com/text/names.html – CrazyChucky Jun 04 '22 at 17:06
  • 1
    Probably dupe of https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – CrazyChucky Jun 04 '22 at 17:52

1 Answers1

2

In fact, creating [0] * m also refers to the same integer:

>>> lst = [0] * 3
>>> [id(i) for i in lst]
[2751327895760, 2751327895760, 2751327895760]

However, for immutable types, the reason why this is not harmful is that they do not operate in place. If you apply an action that seems to be an operation in place to them, you will only get a new object, which makes it impossible for you to modify the referenced integer in place in the list, so other integers will not change because an element is modified:

>>> x = 0
>>> id(x)
2751327895760
>>> x += 1
>>> id(x)
2751327895792

Therefore, for objects such as strings, integers and so on (there is no problem with tuples in most cases, but be careful if there are mutable objects inside tuples! Thanks for @Kelly Bundy's reminder), there is no harm in using list multiplication. When you want to create a list containing the same objects by multiplication, if you can ensure that you will not modify any of them in place, then this operation can be said to be safe.

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31