Nick Lee
Nick Lee

Reputation: 852

How to insert number in 2d list?

How can I insert a value, here 99, into the indices 1 producing [3,4,99] ?

x=[[1,2],[3,4],[5,6]]

x.insert(1[1],99)   #this gives back  'int' object is not subscriptable

print(x)

Upvotes: 0

Views: 66

Answers (2)

Rafael Barros
Rafael Barros

Reputation: 2881

given the list:

x=[[1,2],[3,4],[5,6]]

if you want to insert an element in the middle of the [3,4] element:

x[1].insert(1, 3.5)

will return you

>>> x
[[1, 2], [3, 3.5, 4], [5, 6]]

if you want to add anything to the end of a list, the method for that is append:

x[1].append(5)

now you have:

>>> x
[[1, 2], [3, 3.5, 4, 5], [5, 6]]

Upvotes: 1

khelwood
khelwood

Reputation: 59095

Append the element to the list element index 1 with x[1].append(99).

>>> x=[[1,2],[3,4],[5,6]]
>>> x[1].append(99)
>>> print(x)
[[1, 2], [3, 4, 99], [5, 6]]

Upvotes: 3

Related Questions