Why is this?
Jan-Ole Esleben
esleben at gmail.com
Wed Aug 10 08:35:42 EDT 2005
For the sake of completeness (I didn't copy this message to the list):
> I have a problem with initialization.
> >>> a, b = [[]]*2
> >>> a.append(1)
> >>> b
> [1]
>
> Why is this? Why does not this behave like the below:
You create a single list (inside your brachets) and duplicate a
reference to it. a and b are two references to the same list; this is
just a problem for mutable objects, but I think it's safe to say that
it bites everyone at some point.
> >>> [[], []] == [[]]*2
> True
Obviously, this is not a test for referential identity.
Hope this helps to clear the matter up!
Ole
2005/8/10, Jiri Barton <jbar at hosting4u.cz>:
> Yes, now it is clear!
>
> As always, I should have RTFM, the operator* is not just a syntactic sugar
> and thus does not make copies. You know, my actual scenario was with four
> variables at the time:
>
> a, b, c, d = [], [], [], []
>
> so I was even more tempted to use the previous and wrong approach:-)
>
> Thank you for your explanation. No more errors in my code from now on (oh
> well,...)
>
> jbar
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list