473,756 Members | 4,256 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 1924

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
35777
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
2547
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
2156
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
2937
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
2732
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
9439
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
2081
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
8868
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
5203
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
9287
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10046
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
9886
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
9857
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9722
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7259
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...
1
3817
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
2
3369
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2677
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.