[Tutor] modifying lists of lists

Ed Owens eowens0124 at gmx.com
Thu Oct 4 03:46:27 CEST 2012


I'm just learning Python, so I apologize for a newby question.  I'm trying
to work with lists of lists, the lowest level of which hold one or more
tuples.  I've tried to condense what I've tried.  The code is:
#! Python 2.7
import copy
list = []
for i in range(8):
    list.append((i, i+1))

H = [[list[0], list[2]]]
I = [[list[0], list[2]]]
J = [[list[0], list[2]]]

# H.append(tuple) did it three times for example, and because H=I=J won't
work for the example.
print 'H - list with one list of tuples:', H
H.append([list[1], list[3]])
I.append([list[1], list[3]])
J.append([list[1], list[3]])
print 'H - added list of tuples:', H

# duplicate first list of tuples -> next in sequence
H.insert(1,H[0])
print 'duplicated 1st list in list:', H
# works, but can't edit the second list
H[1].pop(1)
print "First 2 lists can't be independently edited"
print H,'\n'

# try to split up the list and rebuild
J = J[:1] + J[:1] + J[1:]
print 'J:', J
J[1].pop(1)
print "Still can't independently delete tuple:\n", J

# try the copy module
I = I[:1] + copy.deepcopy(I[:1]) + I[1:]
print '\nI:', I
I[1].pop(1)
print "deepcopy requred for independence:\n", I

The third trial works:

>>> 
H - list with one list of tuples: [[(0, 1), (2, 3)]]
H - added list of tuples: [[(0, 1), (2, 3)], [(1, 2), (3, 4)]]
duplicated 1st list in list: [[(0, 1), (2, 3)], [(0, 1), (2, 3)], [(1, 2),
(3, 4)]]
First 2 lists can't be independently edited
[[(0, 1)], [(0, 1)], [(1, 2), (3, 4)]] 

J: [[(0, 1), (2, 3)], [(0, 1), (2, 3)], [(1, 2), (3, 4)]]
Still can't independently delete tuple:
[[(0, 1)], [(0, 1)], [(1, 2), (3, 4)]]

I: [[(0, 1), (2, 3)], [(0, 1), (2, 3)], [(1, 2), (3, 4)]]
deepcopy requred for independence:
[[(0, 1), (2, 3)], [(0, 1)], [(1, 2), (3, 4)]]
>>>

Is there a better way?  I've spent a lot of time looking through the
documentation so I anticipated the results of the first attempt.  I
postulate the split approach didn't work because the assignment was a
pointer to the object, in spite of the splitting up of the list.  By the
way, copy.copy doesn't work.

Thanks for your insights.
Ed
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20121003/37678c71/attachment.html>


More information about the Tutor mailing list