On copying arrays

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Mar 24 10:07:48 EDT 2008


On Mon, 24 Mar 2008 09:52:21 +0000, Duncan Booth wrote:

> The method usually recommended is:
> 
>   best = list(test)
> 
> as it has no side effects

In general, you can't assume *anything* in Python has no side effects, 
unless you know what sort of object is being operated on. Here's an 
example that changes the value of test:

>>> test = iter((1, 2, 3, 4, 5, 6))
>>> best = list(test)
>>> best
[1, 2, 3, 4, 5, 6]
>>> another = list(test)
>>> another
[]


And here's an example that has a rather obvious side-effect:


>>> class Foo(object):
...     def __getitem__(self, n):
...         if n == 3: print "I'm in ur puter, deletin ur files"
...         if 0 <= n < 6: return n+1
...         raise IndexError
...
>>> test = Foo()
>>> best = list(test)
I'm in ur puter, deletin ur files
>>> best
[1, 2, 3, 4, 5, 6]


-- 
Steven



More information about the Python-list mailing list