[Tutor] <mutable>.__mul__

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



----- Original Message -----

> From: eryksun <eryksun at gmail.com>
> To: Albert-Jan Roskam <fomcl at yahoo.com>
> Cc: Python Mailing List <tutor at python.org>
> Sent: Saturday, August 3, 2013 5:19 PM
> Subject: Re: [Tutor] <mutable>.__mul__
> 
> On Sat, Aug 3, 2013 at 10:50 AM, Albert-Jan Roskam <fomcl at yahoo.com> 
> wrote:
>>  # 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.
> 
> You repeated the same list object 4 times in a new list. All that does
> is increment the reference count on the original list:
> 
>     >>> base = [6]
>     >>> sys.getrefcount(base)
>     2
>     >>> seq = list(repeat(base, 4))
>     >>> sys.getrefcount(base)  # +4
>     6
> 
> You'd need to make a shallow copy:
> 
>     >>> base = [6]
>     >>> seq = map(list, repeat(base, 4))
>     >>> sys.getrefcount(base)
>     2
>     >>> seq[0][0] = 666
>     >>> seq
>     [[666], [6], [6], [6]]


Hi Alan, Eryksun,

Thank you. If list.__mul__ is so tricky, why did they implement it the way they did? Are there situations where this behavior could be useful?

Btw, this is one of the rare (very, very rare) cases where I find CRAN R better than Python:

R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows"
Copyright (C) 2012 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: i686-pc-linux-gnu (32-bit)
> rrr <- rep(list(list(6)), 4)
> class(rrr)
[1] "list"
> rrr[[1]][[1]] <- 666
> rrr
[[1]]
[[1]][[1]]
[1] 666


[[2]]
[[2]][[1]]
[1] 6


[[3]]
[[3]][[1]]
[1] 6


[[4]]
[[4]][[1]]
[1] 6
> rrrr <- list()
> for (i in 1:4) { rrrr[[i]] <- list(6) }
> rrrr[[1]][[1]] <- 666
> identical(rrr, rrrr)
[1] TRUE


More information about the Tutor mailing list