1

In the following python code I am trying to create a 2D array, delete an element, and insert a new one in that same specified position. I am able to delete an element with a specified position, however when trying to insert I am getting the error: IndexError: list index out of range.
Thanks for any help

tda = []
for i in range(0,100):
    if i % 10 == 0:
        col = []
        tda.append(col)
    col.append(random.randint(0,10))

del tda[1][1]
tda.insert([1][1],5)
1
  • insert() takes as an argument, the position you want to insert. You are passing a 2D position in the incorrect way. Maybe you wan to do tda[1].insert(1,5)?. Commented Feb 1, 2017 at 20:00

2 Answers 2

1

You're getting the error because you're passing [1][1] as a list index. List indexes must be integers. For example, you could do:

tda[1].insert([5,23,32,53,43])

To insert an entire new "row" into your 2D array. Instead of deleting and inserting however, you should just index into the location you want to change and update it directly:

tda[1][1] = 5
Sign up to request clarification or add additional context in comments.

Comments

0

Try replacing

tda.insert ([1] [1], 5)

with

col = tda [1]
col.insert (1, 5)

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.