"Raj Medhekar" <[email protected]> wrote
I would like to know how I could use the insert method in a
List matrix
OK, A list "matrix" is just a list containing other lists.
TThere is nothing special about it, it is just an ordinary list.
You could do it in two steps:
firstList = M[0]
firstList.insert(0,'pod')
But it is just as easy to do it directly...
eg. for the matrix below
M=[[1,2,3], [3,2,1], [4,3,2]]
if wanted to insert the string 'pod' in list [0] before [1] in list [0]
in M
You said it right the first time. You want to insert 'pod' into list[0], ie
M[0]
So you must call the insert method of that object and specify the index
of the insertion there: 0 in your case.
M[0].insert(...)
M=[[1,2,3], [3,2,1], [4,3,2]]
M.insert([1][1], 'pod')
This makes no sense since insert() takes a single index
because lists (always!) have a single dimension. In M's case
it is a list of 3 elements, which elements just happen to be lists too.
Also insert does not expect the index to be in brackets.
[row[0] for row in M.insert(1, 'pod')]
insert() returns None so the loop in this comprehension breaks,
But you do get the insert syntax right this time. M should now
look like
M=[[1,2,3], 'pod', [3,2,1], [4,3,2]]
M.insert(1,'pod')
M
[[1, 2, 3], 'pod', 'pod', [3, 2, 1], [4, 3, 2]]
You got it right here too but you are inserting it into M not
into the first element of M.
M.insert[0](1,'pod')
So, one more time, it should be
M[0].insert(0,'pod')
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor