473,583 Members | 3,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy a list

Xx r3negade
39 New Member
Consider the following code:
Expand|Select|Wrap|Line Numbers
  1. listA = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
  2. changeCoordinates = ((2, 3), (1, 3))
  4. for coordinateList in changeCoordinates:
  5.     listB = listA[:]
  6.     x = coordinateList[0]
  7.     y = coordinateList[1]
  9.     listB[x][y] = 'foo'
  10.     print "list A: %s" % listA
  11.     print "list B: %s" % listB
listA should never change. But it does. It works the way I expected on a one-dimensional list, but on a two-dimensional list, listA changes. How do I avoid this, and (out of curiosity) why the hell doesn't python just assign the value rather than the reference anyway?
Aug 21 '08 #1
3 2047
469 Recognized Expert Contributor
listB is actually a separate copy of listA, but each of the sub-lists in listB is just a shallow copy of the corresponding sub-list in listA, if that makes any sense. To make a completely independent copy of listA, you will either have to use a loop like this:
Expand|Select|Wrap|Line Numbers
  1. for sub_list in listA:
  2.     listB.append(sublist[:])
or use the deepcopy() function of the copy module:
Expand|Select|Wrap|Line Numbers
  1. import copy
  2. listB = copy.deepcopy(listA)
Hope this helps.
Aug 21 '08 #2
Xx r3negade
39 New Member
OK thanks. And about the second part of my question...is there any logical reason for python to do this? Isn't it inconsistent for the assignment operator to assign a value to some data types and a reference to others? Just wondering why they did this.
Aug 21 '08 #3
469 Recognized Expert Contributor
Not sure. Seems like the only types that get copied as a reference are lists and object types. I think it would make more sense if tuples, strings, and dictionaries got copied as references too, because they can get really huge also. I wonder if there's a way to do shallow copying of those types in Python.
Aug 21 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

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
by: Eric Lilja | last post by:
Hello! Consider the following complete program (with sample output). There's something wrong with my call to std::copy() in the copy constructor of the Unit class. It fails to copy the list. I could solve it by looping manually through the argument's list and call push_back for each element, but I'd like to know what's wrong with my...
by: Martin Ortiz | last post by:
Ugh.... All classes are copy by reference, even if you use "ByVal" and NOT "ByRef" it's still a copy by reference. Of course, as a consequence, if you change any values of the object you passed in, the original object is affected. I expect this with arrays, but not with single objects being passed "ByVal" to functions.... Is there a...
by: xqxu.pzhou | last post by:
I wrote a simple allocator "myAlloc" under the g++ 3.2.3. When it is used by Vector, it works well. But when it is used by List, the codes have errors when compling. the error message is: "no matching function for call to myAlloc<std::_List_node<int> Then I added the following copy constructor to "myAlloc", now it works well. "template...
by: jgscott | last post by:
I've been trawling around for an answer to this question and thought I'd try here. I have a class Graph, which has a std::list<Nodeas a class member. Node it itself a class that makes extensive use of pointers to represent various forms of data in the nodes of graphs, along with pointers to neighboring nodes. This necessitates a deep copy...
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. ...
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...
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...
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...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
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...
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...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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

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.