[docs] [BUG] In python Array module
Zachary Ware
zachary.ware+pydocs at gmail.com
Mon Aug 4 16:37:53 CEST 2014
Hi Raashid,
On Sat, Aug 2, 2014 at 10:27 AM, rashid bhat <raashidbhatt at gmail.com> wrote:
> Hello
>
> The array object on assignment does not create a new object instead it
> creates a reference to the assigned object ( As expected it should create a
> new object).
Why do you expect that? If Python were to create a new object at
every assignment, it would very quickly use up huge amounts of memory
for no good reason, and nobody wants that! Since there's no way to
tell which objects you might want a copy of and which ones you
definitely don't want copied, it takes more than just an assignment to
create a new object. Assignment simply binds the name on the left to
the result of the expression on the right: in your example below, that
means assigning "bar" to the object bound to "foo". Have a look at
http://nedbatchelder.com/text/names.html for a more in-depth
explanation.
The bottom line is, if you want a copy of an object, you'll have to
make it yourself, like so:
>>> import array
>>> foo = array.array('c', 'hello')
>>> bar = foo[:] # this notation means "take a slice of the whole thing"
>>> bar[0] = '\x00'
>>> bar
array('c', '\x00ello')
>>> foo
array('c', 'hello')
Hope this helps,
--
Zach
> Following code would be enough to prove it
>
> import array
>
> foo = array.array("c", "hello")
> bar = foo
>
> bar[0] = "\x00"
>
> print foo[0] gives "\x00" output while it should be hello
>
>
> --
> Regards
> Raashid Bhat
More information about the docs
mailing list