473,796 Members | 2,578 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python List Issue

I've hit a brick wall on something that I'm guessing is pretty simple but
it's driving me nuts. I noticed that with python lists, generally when you
make a copy of a list (ie, List1 = List2) List1 just becomes a reference to
List2 and any modifications done to List1 affects List2. Ok I can live with
this but I want to make a completely seperate copy not attached to the
original in anyway. So then I used this method. List1 = List2[:] . This
seemed to work in most situations, here I can modifiy List1 with out it
affecting List2. But now I've run into an odd problem, and I have no idea
why it's doing what it's doing.
Here's some code

#some globle varibles
bob = [[[0, 0]]]
final = []

############### #########
def ApplySourceFunc (bob, final):
for I in range(1):

for I in range(len(bob)) : #will go through the list and apply
ApplyOperatorsL oop(bob[i][:]) #all the operators to each rule in
the list creating a new list of rules

bob = final
final = []
#end ApplySourceFunc ######

############### #########
def ApplyOperatorsL oop(aList):

iTemp = [] #initial temp, just for validity checking

iTemp = AddGetSpeed(aLi st[:])
if not iTemp == None: #if the operator returns None, then nothing of
value happend
final.append(iT emp)

#end ApplyOperatorsL oop####

############### ##########
def AddGetSpeed(tLi st):
ln = len(tList) #get the length of tList

if ln > 0:
if tList[ln-1][0] == 0:
tList[ln-1][0] = "GetSpeed() "
print "New Rule 'GetSpeed()' Added to the List"
return tList
return None
#end AddGetSpeed#### #####

So, here's what going on. ApplySourceFunc calls ApplyOperatorsL oop which
calls AddGetSpeed. Each function passes the list bob to the next fuction
using the [:] method. For some reason when I get to the AddGetSpeed method
and I do the assignment " tList[ln-1][0] = "GetSpeed() " " this directly
modifies the list bob. Ok, so i was annoyed by that since I was using the
whole [:] method as I passed and used the lists. Then I tried to insert a
temp list into the ApplyOperatorLo op function ( temp2 = aList[:]) and then
pass that into AddGetSpeed. Even when I did this AddGetSpeed modified the
orginial bob list. so, what I'm getting down to is:
How on earth can I make a complete seperate copy of a list with out it
being a attached to the original in any way shape or form so that I can
modifiy if at will and not worry about the original? I've tried every
combonation that I can think of to get this to work, I even wrote my own
copy function but even then I had the same trouble. Until this point
everything was going good, but this has really bugged me

Any ideas, suggestions, comments are greatly appreciated
thanks

Nick
Jul 18 '05 #1
5 1426
Nick L wrote:
I've hit a brick wall on something that I'm guessing is pretty simple but
it's driving me nuts. I noticed that with python lists, generally when you
make a copy of a list (ie, List1 = List2) List1 just becomes a reference to
List2 and any modifications done to List1 affects List2. Ok I can live with
this but I want to make a completely seperate copy not attached to the
original in anyway. So then I used this method. List1 = List2[:] . This
seemed to work in most situations, here I can modifiy List1 with out it
affecting List2. But now I've run into an odd problem, and I have no idea
why it's doing what it's doing.
Here's some code

#some globle varibles
bob = [[[0, 0]]]


I haven't gone through all of your code, but I suspect that the problem
is that objects in the list (in this case, other lists) don't get copied
only get referenced when you do bob[:]. This is expected.

See copy.deepcopy() . It will make sure that everything gets copied and
nothing just referenced (more or less).

http://docs.python.org/lib/module-copy.html

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
Jul 18 '05 #2
See copy.deepcopy() . It will make sure that everything gets copied and
nothing just referenced (more or less).


So far copy.deepcopy() seems to be working perfectly.
Thanks for the input

Nick
Jul 18 '05 #3
On Sun, 27 Mar 2005 09:01:20 GMT, "Nick L" <Fe********@mch si.com>
wrote:
I've hit a brick wall on something that I'm guessing is pretty simple but
it's driving me nuts.
Yes, I've ran across that too a few times.
How on earth can I make a complete seperate copy of a list with out it
being a attached to the original in any way shape or form so that I can
modifiy if at will and not worry about the original?
This routine copies a list of lists.
# Makes a copy of a list of lists
# Containing simple data.
def copylistlist(al ist):
if type(alist) is list:
copy = []
for i in alist:
if type(i) is list:
i = copylistlist(i)
copy.append(i)
return copy

bob = [[[0, 0]]]
final = copylistlist(bo b)

print 'bob:'bob
print 'Final:'final
This still doesn't create new items within the new list. but with
literal data consisting of letters and numbers, it will work.

If you are working with a data tree, you may be able to modify this to
do what you want. Just add a test in the inner loop for the data you
want to modify.

Any ideas, suggestions, comments are greatly appreciated
thanks

Nick


Hope that helps.

Ron_Adam
Jul 18 '05 #4
Thanks, thats a really handy function
"Ron_Adam" <ra****@tampaba y.rr.com> wrote in message
news:mt******** *************** *********@4ax.c om...
On Sun, 27 Mar 2005 09:01:20 GMT, "Nick L" <Fe********@mch si.com>
wrote:
I've hit a brick wall on something that I'm guessing is pretty simple but
it's driving me nuts.


Yes, I've ran across that too a few times.
How on earth can I make a complete seperate copy of a list with out itbeing a attached to the original in any way shape or form so that I can
modifiy if at will and not worry about the original?


This routine copies a list of lists.
# Makes a copy of a list of lists
# Containing simple data.
def copylistlist(al ist):
if type(alist) is list:
copy = []
for i in alist:
if type(i) is list:
i = copylistlist(i)
copy.append(i)
return copy

bob = [[[0, 0]]]
final = copylistlist(bo b)

print 'bob:'bob
print 'Final:'final
This still doesn't create new items within the new list. but with
literal data consisting of letters and numbers, it will work.

If you are working with a data tree, you may be able to modify this to
do what you want. Just add a test in the inner loop for the data you
want to modify.

Any ideas, suggestions, comments are greatly appreciated
thanks

Nick


Hope that helps.

Ron_Adam

Jul 18 '05 #5
Nick L wrote:
I noticed that with python lists, generally when you
make a copy of a list (ie, List1 = List2) List1 just becomes a reference to
List2 and any modifications done to List1 affects List2. Ok I can live with
this but I want to make a completely seperate copy not attached to the
original in anyway.
Although your immediate question has been answered (you wanted
a deep copy, not a shallow one), I think you should take a
step back and consider whether you really need to do that much
copying in the first place.

With the proper approach, I find it's extremely rare to need to
copy anything in a Python program, and rarer still to need
deep copying. Generally, it's better for a function not to
modify objects passed to it, unless that's the purpose of
the function. If a function needs a local copy of an argument,
it should create one itself, and not put the burden on the
caller.

Also, there are some things about your code that suggest you
still do not fully understand how scoping and assignment work
in Python:
def ApplySourceFunc (bob, final):
...
bob = final
final = []
These last two statements do not accomplish anything useful.
All they do is change which objects are referred to by the
parameter names 'bob' and 'final', which are local to the
function, and have no effect on anything outside it.
def ApplyOperatorsL oop(aList):
...
final.append(iT emp)
...


Here you are referring to the global variable 'final', not
the one passed as a parameter to ApplySourceFunc (). To get
the effect you seem to be after, you would need to pass
'final' on as a parameter to ApplyOperatorsL oop().

Here is how I would write this:

def ApplySourceFunc (bob, final):
for item in bob:
ApplyOperatorsL oop(item, final)

def ApplyOperatorsL oop(item, final):
new_item = AddGetSpeed(ite m)
if new_item:
final.append(te mp)

def AddGetSpeed(tLi st):
if tList and tList[-1][0] == 0:
new_tList = tList[:]
new_tList[-1] = new_tList[-1][:]
new_tList[-1][0] = "GetSpeed() "
print "New Rule 'GetSpeed()' Added to the List"
return new_tList
else:
return None

Notice how all the copying is done inside AddGetSpeed(),
it only copies what is needed, and the fact that the copying
is needed is encapsulated within the function; its callers
don't need to know.

I have also made use of some other common Python idioms:

* Whenever possible, it is simpler and clearer to iterate
directly over the items of a list, rather than iterating
over its indices and then indexing it.

* Almost any object can be used as a truth value. Non-empty
lists count as true; empty lists and None count as false.

* The 'and' and 'or' operators short-circuit: if the first
operand determines the result, the second operand is not
evaluated.

* Negative list indices are counted from the end of the
list; e.g. aList[-1] means the last item of aList.

Hope that helps,

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 18 '05 #6

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

Similar topics

68
5903
by: Lad | last post by:
Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.
0
9530
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
10236
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
10182
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
10017
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...
0
5445
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
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4120
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
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
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.