473,799 Members | 3,329 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strange side effect with lists!?

Hello,

I'm new to Python and playing around. I'm confused by the following
behaviour:
l1 = [1] # define list
l2 = l1 # copy of l1 ?
l2,l1 ([1], [1]) l2.extend(l1) # only l2 should be altered !?
l2,l1

([1, 1], [1, 1]) # but also l1 is altered!

So what is the policy of assignment? When is a copy of an object created?
Where to find dox on this?

thanx,

Wolfgang
Jul 18 '05 #1
5 1475
Wo************* **@profactor.at wrote:
l1 = [1] # define list
l2 = l1 # copy of l1 ?
Nope, l2 is l1:
l2 is l1

True

The same happens for any mutable object.

If you want to just do a surface-level copy of l1, you can use l1[:].
But if any of the items in l1 are mutable objects, you probably want to
use copy.deepcopy() .
--
Michael Hoffman
Jul 18 '05 #2
Wo************* **@profactor.at wrote:
Hello,

I'm new to Python and playing around. I'm confused by the following
behaviour:

l1 = [1] # define list
l2 = l1 # copy of l1 ?
No. Creation of another reference to l1.
you can test identity of objects with the 'is' operator : l2 is l1 True
l2,l1
([1], [1])
l2.extend(l 1) # only l2 should be altered !?
No.
l2,l1
([1, 1], [1, 1]) # but also l1 is altered!
Exactly what one would expect !-)
So what is the policy of assignment? When is a copy of an object created?
(please someone correct me if I say any stupidity)

There are two point you need to understand : bindings, and
mutable/immutable types.

With Python, you've got objects, symbols and binding. Unlike languages
like C, a 'variable' (we'd better say 'symbol' or 'name', and you may
also read 'binding') is not the memory address of an object, but a
reference to an object.

The syntax :
l1 = [1] creates a list object, and 'bind' the symbol (or 'name' if you prefer)
'l1' to that list object - which means that l1 holds a reference to the
list object. Now when you're doing l2 = l1 you're binding the symbol l2 to whatever l1 is bound to at this time.

Now there are two kind of objects : mutables and immutables. As
expected, you can modify mutable objects after instanciation, and you
can not modify immutable objects. But you can modify the binding between
a symbol and an immutable object, so when you're doing something like : a = "aaa" and then a = a + "bbb" this do *not* modify the string - what it does is create a new string
made of "aaa" and "bbb" and rebind the symbol 'a' to the newly created
string.

Most Python objects are mutables. Immutable objects are mainly numerics,
strings and tuples.

So what happens with instanciation, modification, bindings, references etc ?

As I said, when you're binding two symbols to the same object (as you
did in your exemple), both symbols reference the same object. Now what
happens when you modify the bound object depends on the "mutability
status" (pardon my poor english) of this object.

Let's have an exemple with an immutable object :

01]>>> a = "aaa"
02]>>> b = a
03]>>> a
04]'aaa'
05]>>> b
06]'aaa'
07]>>> a is b
08]True
09]>>> b = b + "bbb"
10]>>> a
11]'aaa'
12]>>> b
13]'aaabbb'
14]>>> a is b
15]False
16]>>>

Ok, this works as expected : a string being immutable, the statement at
line 09 creates a new string and bind b to this string (or this string
to b if you prefer...). So we now have two distinct string objects

Now with a mutable object :
a = [1]
b = a
a is b True
Ok, now we have to symbols referencing the same mutable object. Since
this is a *mutable* object, modifying it will not create a new object.
So none of the symbols will be rebound :
a.append(2)
a [1, 2] b [1, 2] a is b True
Once again, this works *exactly* as expected - once you understand the
difference between binding and assignement, and the difference between
mutable and immutable objects.

A common pitfall is : a = b = [] This does not create two lists. This create one list and bind both 'a'
and 'b' to this list.

Now back to your problem. You want a copy of the list, not another
reference to the same list. Here the solution is a = [1]
b = a[:]
a is b False a.append(2)
a [1, 2] b [1]


Where to find dox on this?


In the fine manual ?-)
Ok, that's not really obvious from the tutorial. You may want to have a
look here :
http://www.python.org/doc/current/ref/types.html

HTH
Bruno

Jul 18 '05 #3
<Wo************ ***@profactor.a t> wrote:
Hello,

I'm new to Python and playing around. I'm confused by the following
behaviour:
l1 = [1] # define list
l2 = l1 # copy of l1 ?
l2,l1 ([1], [1]) l2.extend(l1) # only l2 should be altered !?
l2,l1

([1, 1], [1, 1]) # but also l1 is altered!

So what is the policy of assignment? When is a copy of an object created?
Where to find dox on this?


Bruno's answer seems very thorough so I'll just try to briefly summarize
the answers:

1. simple assignment (to a bare name, at least), per se, never
implicitly copies objects, but rather it sets a reference to an
object (_another_ reference if the object already had some).

2. a new object is created when you request such creation or perform
operations that require it. Lists are particularly rich in such
operations (see later). Simple assignment to a bare name is not
an operation, per se -- it only affects the name, by making it refer
to whatever object (new, or used;-) is on the righht of the '='.

3. I believe any decent book on Python will cover this in detail.

Now for ways to have a new list object L2 made, with just the same items
and in the same order as another list object L1 ("shallow copy"):

a. import copy; L2 = copy.copy(L1)

This works to shallow-copy _any_ copyable object L1; unfortunately you
do have to import copy first. Module copy also exposes function
deepcopy, for those rare cases in which you wish to recursively also get
copies of all objects to which a "root object" refers (as items, or
attributes; there are some anomalies, e.g., copy.deepcopy(X ) is X when X
is a class, or type...).

b. L2 = list(L1)

I find this is most often what I use - it works (making a new list
object) whatever kind of sequence, iterator, or other iterable L1 may
be. It is also what I recommend you use unless you have some very
specific need best met otherwise.

c. various operations such as...:
L2 = L1 * 1
L2 = L1 + []
L2 = L1[:]
i.e. "multiply by one", "concatenat e the empty list", or "get a slice of
all items". I'm not sure why, but the latter seems to be very popular,
even though it's neither as concise as L1*1 nor as clear and readable as
list(L1).
Alex
Jul 18 '05 #4
On Wed, 13 Oct 2004 14:19:56 +0200, al*****@yahoo.c om (Alex Martelli) wrote:
<Wo*********** ****@profactor. at> wrote:
Hello,

I'm new to Python and playing around. I'm confused by the following
behaviour:
>>> l1 = [1] # define list
>>> l2 = l1 # copy of l1 ?
>>> l2,l1

([1], [1])
>>> l2.extend(l1) # only l2 should be altered !?
>>> l2,l1

([1, 1], [1, 1]) # but also l1 is altered!

So what is the policy of assignment? When is a copy of an object created?
Where to find dox on this?


Bruno's answer seems very thorough so I'll just try to briefly summarize
the answers:

1. simple assignment (to a bare name, at least), per se, never
implicitly copies objects, but rather it sets a reference to an
object (_another_ reference if the object already had some).

2. a new object is created when you request such creation or perform
operations that require it. Lists are particularly rich in such
operations (see later). Simple assignment to a bare name is not
an operation, per se -- it only affects the name, by making it refer
to whatever object (new, or used;-) is on the righht of the '='.

3. I believe any decent book on Python will cover this in detail.

Now for ways to have a new list object L2 made, with just the same items
and in the same order as another list object L1 ("shallow copy"):

a. import copy; L2 = copy.copy(L1)

This works to shallow-copy _any_ copyable object L1; unfortunately you
do have to import copy first. Module copy also exposes function
deepcopy, for those rare cases in which you wish to recursively also get
copies of all objects to which a "root object" refers (as items, or
attributes; there are some anomalies, e.g., copy.deepcopy(X ) is X when X
is a class, or type...).

b. L2 = list(L1)

I find this is most often what I use - it works (making a new list
object) whatever kind of sequence, iterator, or other iterable L1 may
be. It is also what I recommend you use unless you have some very
specific need best met otherwise.

c. various operations such as...:
L2 = L1 * 1
L2 = L1 + []
L2 = L1[:]
i.e. "multiply by one", "concatenat e the empty list", or "get a slice of
all items". I'm not sure why, but the latter seems to be very popular,
even though it's neither as concise as L1*1 nor as clear and readable as
list(L1).

I got curious:
L = range(5)
L [0, 1, 2, 3, 4]

Make it self-referential: L[2]=L
L [0, 1, [...], 3, 4]
import copy
Lc = copy.copy(L)
Lc [0, 1, [0, 1, [...], 3, 4], 3, 4]
Ldc = copy.deepcopy(L )
Ldc [0, 1, [...], 3, 4]

Interesting that the deep copy made the copy self-referential
(i.e., to the copy itself) like the original's reference to
its (different) self:
id(Ldc) == id(Ldc[2]) True

Unlike the shallow copy: id(Lc) == id(Lc[2]) False
....whose middle reference was merely copied and sill refers to L: id(Lc[2]) == id(L) True

But like the original: id(L) == id(L[2])

True

I'm impressed ;-)

Regards,
Bengt Richter
Jul 18 '05 #5
Bengt Richter wrote:
I got curious:
L = range(5)
L [0, 1, 2, 3, 4]
<various manipulations of a recursive data structure snipped>
I'm impressed ;-)


I find it impressive that recursive data structures involving builtin
types manage to avoid printing out infinite regressions of themselves.
class C: def __init__(self, val):
self.val = val
def __repr__(self):
return "<C %s>" % self.val
l = range(5)
l [0, 1, 2, 3, 4] c = C(l)
c <C [0, 1, 2, 3, 4]> l[2] = c
l [0, 1, <C [...]>, 3, 4] c

<C [0, 1, <C [...]>, 3, 4]>
Jul 18 '05 #6

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

Similar topics

9
4342
by: Kathryn | last post by:
Hiya I have a problem with using some client side and server side scripting together in an ASP. I'm using VBScript. What I'm trying to achieve is this - - Page loads up and some server side vbscript reads the database and populates a listbox on the page with the first field from each record in the recordset. This works fine. - User selects an option on the listbox and, using the OnChange, I
1
2790
by: Luigi | last post by:
I noted a particular behavior shown by IE. Look at the simple page attached at the bottom of the post. In it, there is a box floated with the float property and another box that jumps it with the clear property. Show the page in IE and highlight (using the mouse) some text in the blue box (include some line on the side of the gray box). Then click anywhere (out of the highlight zone). RESULT: some text lines (on the side of the gray...
3
2308
by: Andrew Mayo | last post by:
(note: reason for posting here; browser helper object is written in C++; C++ developers tend to know the intricacies of message handling; this looks like a Windows messaging issue) Microsoft very kindly make available a DLL (the browser helper DLL) which allows you to trap and disable the context menu (right mouse click) and various 'built-in' browser accelerators (such as ctrl+P which brings up the print dialogue, and F5, which will...
9
2025
by: bonono | last post by:
Hi, I initially thought that generator/generator expression is cool(sort of like the lazy evaluation in Haskell) until I notice this side effect. >>>a=(x for x in range(2)) >>>list(a) >>>list(a)
31
6652
by: Bjørn Augestad | last post by:
Below is a program which converts a double to an integer in two different ways, giving me two different values for the int. The basic expression is 1.0 / (1.0 * 365.0) which should be 365, but one variable becomes 364 and the other one becomes 365. Does anyone have any insight to what the problem is? Thanks in advance. Bjørn
14
1892
by: James Wong | last post by:
Hi! everybody, I'm facing a quite strange download problem. I use the following code to download an XML file to client side: With Response ' clear buffer Call .Clear() ' specify the type of the downloadable file
20
1684
by: SpreadTooThin | last post by:
I have a list and I need to do a custom sort on it... for example: a = #Although not necessarily in order def cmp(i,j): #to be defined in this thread. a.sort(cmp) print a
6
4918
by: Senthil | last post by:
Hi, Whenever i read a C++ book or a newsgroup posting, i come across the terms like " before the side effects completes" , "destructor with side effects" etc. What is this side effect mean in C++ world? Is it like something that is not desired but happens automatically and we cannot prevent it? Would be great if someone throws light on this. Thanks,
20
2245
by: Pilcrow | last post by:
This behavior seems very strange to me, but I imagine that someone will be able to 'explain' it in terms of the famous C standard. -------------------- code ----------------------------------- #include <stdio.h> int main (void) { char xx="abcd"; char * p1 = xx;
0
9687
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
9541
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
10485
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
7565
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
6805
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
5463
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
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
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.