1

I'm looking for a method of inserting values to 2D lists in Python. My sample list is as follows:

List= [ ['A', 'B'], ['C', 'D'] ]

I would like to insert a value at the beginning of each list within my List, so that it would look like this:

List = [ ['#','A', 'B'], ['#','C', 'D'] ]

I have written a function as follows:

def Foo(l):
    rows = len(l)
    cols = len(l[0])
    for row in xrange(rows):
        l.insert(row, '#')

But that has given me the following output:

List= [ '#', '#', ['A', 'B'], ['C', 'D'] ]
1
  • 1
    for row in l: row.insert(0, '#') Commented Apr 4, 2016 at 3:00

1 Answer 1

5

when you do l.insert() it adds an item to l not the sub lists, to iterate over the sub lists you can do:

for row in l:
    row.insert(0,"#")

Or using xrange:

for i in xrange(len(l)):
    l[i].insert(0,"#")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.