Bug?
Richard Jones
richard at bizarsoftware.com.au
Tue Jul 24 21:04:12 EDT 2001
On Wed, 25 Jul 2001 10:39, Ricardo Correia wrote:
> Hi
>
> ---------------------------------------------------
> mainlist = [1, 2, 3, 4, 5]
> copy = mainlist
>
> for item in copy:
> print item,
> mainlist.remove(item)
> ---------------------------------------------------
>
> Shouldn't this produce '1 2 3 4 5'?
>
> I only get '1 3 5' and unfortunately because of this my program doesn't
> work.
In the above, "copy" is not a copy of "mainlist".
>>> mainlist = [1, 2, 3, 4, 5]
>>> copy = mainlist
>>> id(copy)
135189396
>>> id(mainlist)
135189396
>>> copy = mainlist[:]
>>> id(copy)
135077076
>>> for item in copy:
... print item,
... mainlist.remove(item)
...
1 2 3 4 5
>>>
The second copy assignment uses the slice mechanism to take a true copy of
the contents of mainlist.
Richard
--
Richard Jones
richard at bizarsoftware.com.au
Senior Software Developer, Bizar Software (www.bizarsoftware.com.au)
More information about the Python-list
mailing list