[Tutor] <mutable>.__mul__
eryksun
eryksun at gmail.com
Sat Aug 3 17:19:39 CEST 2013
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]]
More information about the Tutor
mailing list