On copying arrays

E

ernesto.adorio

Is there a conceptual difference between
best =test[:]
and
best = [x for x in test] ?
test is a list of real numbers. Had to use the second form to avoid a
nasty bug
in a program I am writing. I have to add too that I was using psyco
in Python 2.5.1.

Regards,
Ernie.
 
B

bearophileHUGS

ernesto:

best = list(test)

may be faster than:

best = [x for x in test]

Bye,
bearophile
 
D

Duncan Booth

Is there a conceptual difference between
best =test[:]
and
best = [x for x in test] ?
test is a list of real numbers. Had to use the second form to avoid a
nasty bug
in a program I am writing. I have to add too that I was using psyco
in Python 2.5.1.
The first one will only copy sliceable sequences and will give you a result
of the same type as test (e.g. if test is a tuple so is best).

The second one will copy any sequence, always results in a list and as a
side effect assigns a value to 'x'.

The method usually recommended is:

best = list(test)

as it has no side effects, copies any sequence and may be faster than the
list comprehension. As with the second of your examples it always gives you
a list.
 
S

Steven D'Aprano

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:

.... 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
....[1, 2, 3, 4, 5, 6]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top