[Tutor] <mutable>.__mul__

Albert-Jan Roskam fomcl at yahoo.com
Sat Aug 3 16:50:49 CEST 2013


Hi,

Suppose I initialize  a list (letś say it's a record) to e.g all zeroes, or all sixes. Suppose, further, that I use "*" for this (which is a nice an clean way). Then how do I get rid of the scary thing that the list items are "interdependent"? See below what I mean with that.


# repeating items of a list using list.__mul__

>>> y = 4 * [[6]]
>>> y
[[6], [6], [6], [6]]
>>> # is there something I can do right *here* to make the list items independent? (copy.deepcopy does not work)

>>> y[0][0] = 666
>>> y
[[666], [666], [666], [666]]    # look mom, I changed all four items in one go! :-(


# repeating items of a list using itertools.repeat

>>> from itertools import repeat
>>> yyy = repeat([6], 4)
>>> yyy
repeat([6], 4)
>>> yyy = list(yyy)
>>> yyy
[[6], [6], [6], [6]]
>>> yyy[0][0] = 666
>>> yyy
[[666], [666], [666], [666]]  # same thing: assignment of one item changes all items.


# the not-so-scary alternative
>>> yy = [[6] for i in range(4)]
>>> yy
[[6], [6], [6], [6]]
>>> yy[0][0] = 666
>>> yy
[[666], [6], [6], [6]]


Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


More information about the Tutor mailing list