473,775 Members | 3,863 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Preferred method for "Assignment by value"

As a relative new comer to Python, I haven't done a heck of a lot of
hacking around with it. I had my first run in with Python's quirky (to
me at least) tendency to assign by reference rather than by value (I'm
coming from a VBA world so that's the terminology I'm using). I was
surprised that these two cases behave so differently

test = [[1],[2]]
x = test[0]
x[0] = 5
test
>>[[5],[2]]
x = 1
test
>>>[[5],[2]]
x
>>1
Now I've done a little reading and I think I understand the problem...
My issue is, "What's the 'best practise' way of assigning just the
value of something to a new name?"

i.e.
test = [[1,2],[3,4]]
I need to do some data manipulation with the first list in the above
list without changing <test>
obviously x = test[0] will not work as any changes i make will alter
the original...
I found that I could do this:
x = [] + test[0]

that gets me a "pure" (i.e. unconnected to test[0] ) list but that
concerned me as a bit kludgy

Thanks for you time and help.
Jun 27 '08 #1
10 1743
ha*******@gmail .com wrote:
As a relative new comer to Python, I haven't done a heck of a lot of
hacking around with it. I had my first run in with Python's quirky (to
me at least) tendency to assign by reference rather than by value (I'm
coming from a VBA world so that's the terminology I'm using). I was
surprised that these two cases behave so differently

test = [[1],[2]]
x = test[0]
x[0] = 5
test
>>>[[5],[2]]
x = 1
test
>>>[[5],[2]]
x
>>>1

Now I've done a little reading and I think I understand the problem...
My issue is, "What's the 'best practise' way of assigning just the
value of something to a new name?"

i.e.
test = [[1,2],[3,4]]
I need to do some data manipulation with the first list in the above
list without changing <test>
obviously x = test[0] will not work as any changes i make will alter
the original...
I found that I could do this:
x = [] + test[0]

that gets me a "pure" (i.e. unconnected to test[0] ) list but that
concerned me as a bit kludgy

Thanks for you time and help.
If you want a *copy* of an object (or portion thereof), you must
explicitly *specify* a copy. THere are different ways of doing that
depending on the object in question.

Lists (and slices thereof) can be copied to a new list withthe slice syntax:
L[1:4] will copy a limited portion, and
L[:] will copy the whole list.
The kind of copy is only one level deep -- the contents of the copy
will be references to the contents of L

Dictionaries have a copy method that creates a new dictionary.
Again this copy is only one level deep.

The copy modules provides a more general way to copy objects. It
provides the ability to produce both shallow and deep copies.

A small note: In a dozen years of programming in Python, I've used
these various copy methods perhaps a dozen times or less. If you find
you are copying structures often, you are probably not using Python as
effectively as you could.

Gary Herron
Jun 27 '08 #2
On Apr 15, 10:23 am, hall.j...@gmail .com wrote:
As a relative new comer to Python, I haven't done a heck of a lot of
hacking around with it. I had my first run in with Python's quirky (to
me at least) tendency to assign by reference rather than by value (I'm
coming from a VBA world so that's the terminology I'm using). I was
surprised that these two cases behave so differently

test = [[1],[2]]
x = test[0]
x[0] = 5
test>>[[5],[2]]

x = 1
test
>>[[5],[2]]
x
>1

Now I've done a little reading and I think I understand the problem...
My issue is, "What's the 'best practise' way of assigning just the
value of something to a new name?"

i.e.
test = [[1,2],[3,4]]
I need to do some data manipulation with the first list in the above
list without changing <test>
obviously x = test[0] will not work as any changes i make will alter
the original...
I found that I could do this:
x = [] + test[0]

that gets me a "pure" (i.e. unconnected to test[0] ) list but that
concerned me as a bit kludgy

Thanks for you time and help.

I think you understand the concept, basically you want to make a copy.

Ether of these are acceptable:
x = test[0][:]
OR
x = list(test[0])

this will also work:

import copy
x = copy(test[0])

Matt
Jun 27 '08 #3
On Apr 15, 6:23*pm, hall.j...@gmail .com wrote:
As a relative new comer to Python, I haven't done a heck of a lot of
hacking around with it. I had my first run in with Python's quirky (to
me at least) tendency to assign by reference rather than by value (I'm
coming from a VBA world so that's the terminology I'm using). I was
surprised that these two cases behave so differently
Perhaps it is better to think that you bind the name 'x' to the object
'42' when you write 'x=42'.
test = [[1],[2]]
x = test[0]
x[0] = 5
test>>[[5],[2]]

x = 1
test
>>[[5],[2]]
x
>1

Now I've done a little reading and I think I understand the problem...
My issue is, "What's the 'best practise' way of assigning just the
value of something to a new name?"

i.e.
test = [[1,2],[3,4]]
I need to do some data manipulation with the first list in the above
list without changing <test>
obviously x = test[0] will not work as any changes i make will alter
the original...
I found that I could do this:
x = [] + test[0]

that gets me a "pure" (i.e. unconnected to test[0] ) list but that
concerned me as a bit kludgy

Thanks for you time and help.
To create a new list with the same elements as a sequence seq, you can
use list(seq). 'list' is the type of lists, it is also a 'constructor'
for list objects (the same goes for other common buit-in types, such
as 'int', 'float', 'str', 'tuple', 'dict').

E.g.
>>foo = [1, 2, 3]
bar = list(foo)
foo[0] = 4
foo
[4, 2, 3]
>>foo = [1, 2, 3]
bar = list(foo)
bar[0] = 4
bar
[4, 2, 3]
>>foo
[1, 2, 3]
>>>
HTH

--
Arnaud

Jun 27 '08 #4
http://effbot.org/zone/python-objects.htm still says it best.

mt
Jun 27 '08 #5
I think the fundamental "disconnect " is this issue of mutability and
immutability that people talk about (mainly regarding tuples and
whether they should be thought of as static lists or not)

Coming from VBA I have a tendency to think of everything as an
array...

So when I create the following

test=[1,2],[3,4],[5,6] I'm annoyed to find out that I can change do
the following
test[1][1] = 3
but i can't do
test[1] = [3,3]
and so I throw tuples out the window and never use them again...

The mental disconnect I had (until now) was that my original tuple was
in affect "creating" 3 objects (the lists) within a 4th object (the
tuple)... Previously, I'd been thinking of the tuple as one big object
(mentally forcing them into the same brain space as multi-dimensional
arrays in VBA)

This was a nice "aha" moment for me...
Jun 27 '08 #6
ha*******@gmail .com wrote:
Thank you both, the assigning using slicing works perfectly (as I'm
sure you knew it would)... It just didn't occur to me because it
seemed a little nonintuitive... The specific application was

def dicttolist (inputdict):
finallist=[]
for k, v in inputdict.iteri tems():
temp = v
temp.insert(0,k )
finallist.appen d(temp)

return finallist
Maybe,

finallist = [[k] + v for k, v in inputdict.iteri tems()]

the list concatenation creating new lists.

Duncan
Jun 27 '08 #7
ha*******@gmail .com schrieb:
by changing temp = v[:] the code worked perfectly (although changing
temp.insert(0,k ) to temp = [k] + temp also worked fine... I didn't
like that as I knew it was a workaround)
So the for body now looks like this?:

temp = v[:]
temp.insert(0, k)
finallist.appen d(temp)

It can still be clarified and simplified to this (may also be faster):

temp = [k] + v
finallist.appen d(temp)

Which one do you like better :)?

Robin
Jun 27 '08 #8
On Apr 15, 7:23 pm, hall.j...@gmail .com wrote:

test = [[1],[2]]
x = test[0]
Python names are pointer to values. Python behaves like Lisp - not
like Visual Basic or C#.

Here you make x point to the object which is currently pointed to by
the first element in the list test. If you now reassign test[0] = [2],
x is still pointing to [1].

x[0] = 5
test>>[[5],[2]]

x = 1
Here you reassign x to point to an int object vith value 1. In other
words, x is no longer pointing to the same object as the first element
in the list test.

That is why get this:
test
>>[[5],[2]]
x
>1
test = [[1,2],[3,4]]
I need to do some data manipulation with the first list in the above
list without changing <test>
obviously x = test[0] will not work as any changes i make will alter
the original...
You make a slice, e.g.

x = [from:until:stri de]

Now x is pointing to a new list object, containing a subset of the
elements in list. If you reassign elements in x, test will still be
the same.

The point to remember, is that a list does not contain values, but
pointers to values. This can be very different from arrays in C, VB,
Java or C#:

a = [1,2,3,4,5] in Python

is different from

int a[] = {1,2,3,4,5};

The Python statement makes a list of five pointers, each pointing to
an immutable int object on the heap. The C statement allocates a
buffer of 5 ints on the stack.

If you can read C, the Python statement a = [1,2,3,4,5] is thus
similar to something like

int **a, i, amortize_paddin g=4;
a = malloc(5 * sizeof(int*) + amortize_paddin g*sizeof(int*)) ;
for (i=0; i<5; i++) {
a[i] = malloc(sizeof(i nt));
*a[i] = i;
}









Jun 27 '08 #9
On Apr 15, 8:19 pm, hall.j...@gmail .com wrote:
Coming from VBA I have a tendency to think of everything as an
array...
Coding to much in Visual Basic, like Fortran 77, is bad for your mind.
Jun 27 '08 #10

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

Similar topics

17
3068
by: Tobiah | last post by:
Ok, I miss the idiom that my other languages use, something like: while( foo = getmore()){ process(foo); }
11
2655
by: ajikoe | last post by:
Hello, I used Visual C# Standard Edition. I want to comment my program using xml commentary method, I don't know why if I use value and example tag, it is not working / showed in the html result. for example I have Property ///<value>this is in description</value> ///<example>this is in Example</example> public int A{
10
3945
by: John Bailo | last post by:
I want to pass a SqlCommand object as a input parameter to a method. I want to pass the SqlCommand "by value" so that any updates to the original object are *not* reflected in the object within my method. How can I do this?
1
8031
by: Java Guy | last post by:
I'm trying to view a web page. IE tells me there are (Java?) errors on the page. Here they are: Line: 15 Char: 7 Error: Wrong number of arguments or invalid propert assignment Code: 0 URL: http://(address.of.my.webcam):port/LiveView.html and
1
7084
by: mark | last post by:
Forgive me if this seems like a stupid question but I need help... I'm trying to do a simple online form that emails me the results from a few fields. Here is the code: <form action="http://cm1web1/WebSurveyComponents/script/ processform.asp" method="post">
1
5143
by: mithunmo | last post by:
If I run the below program . I get the following error message Can't call method "value" on an undefined value at C:/Perl/site/lib/Win32/IE/Mec hanize.pm line 900. Please let me know your inputs on the same #!c:\perl\bin\perl.exe use strict;
2
2159
by: mithunmo | last post by:
I am trying to automate the process of filling up the webforms and do a submit . I have the below program written but If I run the program . I get the following error message Can't call method "value" on an undefined value at C:/Perl/site/lib/Win32/IE/Mec hanize.pm line 900. Please let me know your inputs on the same #!c:\perl\bin\perl.exe
11
2524
by: markryde | last post by:
Hello, Followed here is a simplified code example of something which I try to implement; in essence , I want to assign a value to a return value of a method is C. I know, of course, that in this example I can get this by newskb->iph = iphdr (this also appears in a commented line in the example below) ; but I want to achieve the same where the left side is : ip_hdr(newskb). Alas, if I try this , I get a compilation error about line 25....
0
9623
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
10276
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...
1
10055
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
9918
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
7465
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
6720
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
5488
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4023
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
2855
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.