473,698 Members | 2,025 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best way to create a copy of a list

Hi all

Assume a 2-dimensional list called 'table' - conceptually think of it
as rows and columns.

Assume I want to create a temporary copy of a row called 'row',
allowing me to modify the contents of 'row' without modifying the
contents of 'table'.

I used to fall into the newbie trap of 'row = table[23]', but I have
learned my lesson by now - changing 'row' also changes 'table'.

I have found two ways of doing it that seem to work.

1 - row = table[23][:]

2 - row = []
row[:] = table[23]

Are these effectively identical, or is there a subtle distinction which
I should be aware of.

I did some timing tests, and 2 is quite a bit faster if 'row'
pre-exists and I just measure the second statement.

TIA

Frank Millman

Apr 4 '06 #1
7 1922

Frank Millman wrote:
Hi all

Assume a 2-dimensional list called 'table' - conceptually think of it
as rows and columns.

Assume I want to create a temporary copy of a row called 'row',
allowing me to modify the contents of 'row' without modifying the
contents of 'table'.

I used to fall into the newbie trap of 'row = table[23]', but I have
learned my lesson by now - changing 'row' also changes 'table'.

I have found two ways of doing it that seem to work.

1 - row = table[23][:]

2 - row = []
row[:] = table[23]

Are these effectively identical, or is there a subtle distinction which
I should be aware of.

I did some timing tests, and 2 is quite a bit faster if 'row'
pre-exists and I just measure the second statement.

you could use list()

row = list(table[23])

The effect is the same, but it's nicer to read.
See also the copy module.

Apr 4 '06 #2
Frank Millman wrote:
I have found two ways of doing it that seem to work.

1 - row = table[23][:]

2 - row = []
row[:] = table[23]

Are these effectively identical, or is there a subtle distinction which
I should be aware of.

I did some timing tests, and 2 is quite a bit faster if 'row'
pre-exists and I just measure the second statement.


quite a bit ? maybe if you're using very short rows, and all rows
have the same length, but hardly in the general case:

python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] = data[23]"
100000 loops, best of 3: 5.35 usec per loop

python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]"
100000 loops, best of 3: 4.81 usec per loop

(for constant-length rows, the "row[:]=" form saves one memory
allocation, since the target list can be reused as is. for longer rows,
other things seem to dominate)

</F>

Apr 4 '06 #3

Fredrik Lundh wrote:
Frank Millman wrote:
I have found two ways of doing it that seem to work.

1 - row = table[23][:]

2 - row = []
row[:] = table[23]

Are these effectively identical, or is there a subtle distinction which
I should be aware of.

I did some timing tests, and 2 is quite a bit faster if 'row'
pre-exists and I just measure the second statement.


quite a bit ? maybe if you're using very short rows, and all rows
have the same length, but hardly in the general case:

python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] = data[23]"
100000 loops, best of 3: 5.35 usec per loop

python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]"
100000 loops, best of 3: 4.81 usec per loop

(for constant-length rows, the "row[:]=" form saves one memory
allocation, since the target list can be reused as is. for longer rows,
other things seem to dominate)

</F>


Interesting. My results are opposite.

python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] =
data[23]"
100000 loops, best of 3: 2.57 usec per loop

python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]"
100000 loops, best of 3: 2.89 usec per loop

For good measure, I tried Rune's suggestion -

python -mtimeit -s "data=[range(100)]*100" "row = list(data[23])"
100000 loops, best of 3: 3.69 usec per loop

For practical purposes these differences are immaterial - I do not
anticipate huge quantities of data.

If they are all equivalent from a functional point of view, I lean
towards the second version. I agree with Rune that the third one is
nicer to read, but somehow the [:] syntax makes it a bit more obvious
what is going on.

Thanks

Frank

Apr 4 '06 #4
"Frank Millman" <fr***@chagford .com> writes:
Interesting. My results are opposite.
I got the same here (cPython 2.4.1):

godoy@jupiter ~ % python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] = data[23]"
1000000 loops, best of 3: 1.15 usec per loop
godoy@jupiter ~ % python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]"
100000 loops, best of 3: 1.42 usec per loop
godoy@jupiter ~ % python -mtimeit -s "data=[range(100)]*100" "row = list(data[23])"
100000 loops, best of 3: 1.93 usec per loop
godoy@jupiter ~ %
If they are all equivalent from a functional point of view, I lean
towards the second version. I agree with Rune that the third one is
nicer to read, but somehow the [:] syntax makes it a bit more obvious
what is going on.


I prefer the third option for readability. It makes it clear that I'll get a
*new* list with the 23rd row of data. Just think: how would you get the 1st
column of the 23rd row?
a = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
a [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] a[1] [2, 3] a[1][1] 3 a[1][:] [2, 3]


Someone might think that the "[:]" means "all columns" and the syntax to be
equivalent to "data[23]".
--
Jorge Godoy <go***@ieee.org >

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
Apr 4 '06 #5
Frank Millman <fr***@chagford .com> wrote:
...
If they are all equivalent from a functional point of view, I lean
towards the second version. I agree with Rune that the third one is
nicer to read, but somehow the [:] syntax makes it a bit more obvious
what is going on.


I vastly prefer to call list(xxx) in order to obtain a new list with the
same items as xxx -- couldn't be more obvious than that.

You can't claim it's obvious that xxx[:] *copies* data -- because in
Numeric, for example, it doesn't, it returns an array that *shares* data
with xxx. So, the [:] notation sometimes copies and sometimes does not,
list list(...) always copies -- if I want to ensure that a copy does
happen, then list(...) is the more obvious and readable choice.
Alex
Apr 4 '06 #6
al*****@yahoo.c om (Alex Martelli) writes:
I vastly prefer to call list(xxx) in order to obtain a new list with the
same items as xxx -- couldn't be more obvious than that.

You can't claim it's obvious that xxx[:] *copies* data


Heh, it wasn't obvious that list(xxx) copies data either (I thought of
it as being like a typecast), but I just checked, and it does copy.
I'll have to remember to do it like that. I do like it better than
xxx[:] which is what I'd been using because I remember seeing that the
copy module does it that way.
Apr 4 '06 #7

Alex Martelli wrote:
Frank Millman <fr***@chagford .com> wrote:
...
If they are all equivalent from a functional point of view, I lean
towards the second version. I agree with Rune that the third one is
nicer to read, but somehow the [:] syntax makes it a bit more obvious
what is going on.


I vastly prefer to call list(xxx) in order to obtain a new list with the
same items as xxx -- couldn't be more obvious than that.

You can't claim it's obvious that xxx[:] *copies* data -- because in
Numeric, for example, it doesn't, it returns an array that *shares* data
with xxx. So, the [:] notation sometimes copies and sometimes does not,
list list(...) always copies -- if I want to ensure that a copy does
happen, then list(...) is the more obvious and readable choice.
Alex


Thanks very much for the detailed explanation.

Frank

Apr 5 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
35772
by: Andreas Kuntzagk | last post by:
Hi, There are three ways to (shallow)copy a list l I'm aware of: >>> l2=list(l) >>> l2=l >>> l2.copy.copy(l) Are there any differences? Are there more (reasonable) ways? I think the first is the most pythonic, second looks more like this other
5
2544
by: Daniel Pryde | last post by:
Hi everyone. I was wondering if anyone might be able to help me out here. I'm currently looking to find the quickest way to find a best fit match in a large array. My problem is that I have an array of, say, 600*400, which contains a value at each point, and I need to find the value in that array which is closest to the input value. It's basically some euclidean distances that I've calculated, and I need to be able to find the best matches...
4
2147
by: Chuck Ritzke | last post by:
I keep asking myself this question as I write class modules. What's the best/smartest/most efficient way to send a large object back and forth to a class module? For example, say I have a data access module that creates a large disconnected dataset from a database. I want to pass that dataset back to the calling program. And then perhaps I want to send that dataset to another class module. At first it seems that the "object oriented"...
2
2933
by: Mike Button | last post by:
Hello all, I am really really desperate on what I should do, and I am asking for help from anyone in this newsgroup, here's the situation: I am creating a form that is being run on a server where there is no scripts allowed running (the software is from Opentext called Livelink)- therefore I need javascript to do the tasks listed below: 1. validate the form - this has been completed 2. pop up another window that will go ahead and...
14
2725
by: Howard | last post by:
Hi, I recently had a problem where I decided to store objects in a vector. (Previously, I had always stored pointers in vectors). Well, naturally, when storing an object in a vector, using push_back, the object I had in hand was getting copied (twice, in fact). That led to a problem, in that my object contained a "handle" to another object, and when the object being pushed went out of scope and was destroyed, the referenced object was...
136
9379
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their code was littered with document.all and eval, for example, and I wanted to create a practical list of best practices that they could easily put to use. The above URL is version 1.0 (draft) that resulted. IMO, it is not a replacement for the FAQ,...
1
2021
by: Chris Uwins | last post by:
Hi there, i know theres a number of ways I can achieve this but want to know the best, (but still quite simple). Up until a year ago I never used Access but have designed a few databases for work. I am working on Access 2000. I have basic SQL/VB skills - and am pretty accomplished at putting the databases together. Anyway...I've created a database to keep track of "Dayworks" we are
7
8859
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I want my users to be able to select a report, click on a command button on a form, which will then automatically create the report as a pdf file and save it to the user's machine. I am using Adobe Acrobat (5.0 I think) and have Adobe Distiller as a
56
5167
by: Zytan | last post by:
Obviously you can't just use a simple for loop, since you may skip over elements. You could modify the loop counter each time an element is deleted. But, the loop ending condition must be checked on each iteration, since the Count changes as you delete elements. I would think it is guaranteed to be computed each time, and not cached. So, is this the best way?
0
8668
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9152
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9014
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6515
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4358
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4612
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
1995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.