| Reply | « Previous Thread | Next Thread » |
|
I was very surprised about the result of following code:
Code:
list0 = [u"Zero",u"One",u"Two"] list1 = list0 list1.insert(0,list1.pop(1)) print list1 print list0 >>> [u'One', u'Zero', u'Two'] [u'One', u'Zero', u'Two'] >>> Why does the origin list (list0) also become changed? |
|
Join Date: Oct 2007
Posts: 2,841
Location: Deva, Romania
Offline
Forum Nokia Champion
|
|
Because list1 points to list0, so to speak. If you want to prevent list0 from changing:
Code:
list0 = [u"Zero",u"One",u"Two"] list1 = list(list0) list1.insert(0,list1.pop(1)) print list1 print list0 [u'One', u'Zero', u'Two'] [u'Zero', u'One', u'Two'] |
|
That’s very interesting.
![]() I never have seen such effect in other program languages, I think. When writing an assigning like X = Y afterwards it should not make any difference for X what happens with Y But thanks for your alternative code example! ![]() |
|
You could also use the slice operator with the default values:
Code:
list0 = [u"Zero",u"One",u"Two"] list1 = list0[:] list1.insert(0,list1.pop(1)) print list1 print list0 http://igordsm.googlepages.com |
|
Hi guys, I think I have a similar problem (python noob here).
I was trying to do a list of lists this way: Code:
>>> list1=[[0]*2]*3 >>> list1 [[0, 0], [0, 0], [0, 0]] Code:
>>> list1[0][1]=1 >>> list1 [[0, 1], [0, 1], [0, 1]] Code:
>>> list2=[[0 for j in range(2)] for i in range(3)] >>> list2 [[0, 0], [0, 0], [0, 0]] >>> list2[0][1]=1 >>> list2 [[0, 1], [0, 0], [0, 0]] Can someone please explain? Thanks in advance! |
|
Quote:
Immutable types include: boolean, complex, float, int, long, none, string, tuple, type, unicode. Mutable types include: class, dictionary, function, instance, list, module. |
|
hum... so if I follow you right, when I do [[0]*2]*3 it fails because while in [0]*2 the multiplication operates on an immutable type (int 0 - actually why isnt [0] considered a list too?), in [[0]*2]*3 it does no longer so (cause now it operates on a list [0,0])
That will take a while to soak in, but I can see it makes sense... Anyway, thanks for your reply, it was helpful |
| Reply | « Previous Thread | Next Thread » |
| Thread Tools | Search this Thread |
|---|---|
| Rate This Thread | |
| Thread | Thread Starter | Forum | Replies | Last Post |
|---|---|---|---|---|
| Trick to prevent Python from closing on red key press. | y.a.k | Python | 19 | 2009-07-28 15:16 |
| Python for Series 60 released on Forum Nokia! | eriksmartt | Python | 5 | 2009-07-14 18:00 |
| heap size in python extensions? | ecostanza | Python | 0 | 2008-04-24 14:59 |
| Ask The Expert: dcrocha on Python | Nokia Ron | Interviews & Ask the Experts | 15 | 2008-04-21 21:51 |
| Question about Databases supportet by Python | GSM1 | Python | 1 | 2006-05-30 13:39 |