473,467 Members | 1,565 Online
Bytes | Software Development & Data Engineering Community
Create 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 1714
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.iteritems():
temp = v
temp.insert(0,k)
finallist.append(temp)

return finallist
Maybe,

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

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.append(temp)

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

temp = [k] + v
finallist.append(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:stride]

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_padding=4;
a = malloc(5 * sizeof(int*) + amortize_padding*sizeof(int*));
for (i=0; i<5; i++) {
a[i] = malloc(sizeof(int));
*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
On Apr 15, 3:51*pm, sturlamolden <sturlamol...@yahoo.nowrote:
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.
The distinction you're looking for is:

VB:
set a= collection
a= collection

Every assignment is a 'set'.
Jun 27 '08 #11

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

Similar topics

17
by: Tobiah | last post by:
Ok, I miss the idiom that my other languages use, something like: while( foo = getmore()){ process(foo); }
11
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...
10
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...
1
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:...
1
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...
1
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...
2
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...
11
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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,...
0
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...
1
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...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

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.