Inserting elements to a list in Python

Question:

I have a list Cb. I want to insert element 0 at len(Cb[0]) but I am getting an error. I present the expected output.

Cb=[[1.0, 0.0, 0.0]] 

for i in range(0,len(Cb[0])):
    Cb=Cb[0].insert(0,len(Cb[0])) 
print(Cb)

The error is

in <module>
    Cb=Cb[0].insert(0,len(Cb[0]))

TypeError: 'NoneType' object is not subscriptable

The expected output is

[[1.0, 0.0, 0.0, 0.0]]
Asked By: isaacmodi123

||

Answers:

Simply append to the inner list using Cb[0].append(0)

Answered By: BarrY Allen

list.insert() returns None thats why you’re getting an error try this :

Cb = [[1.0, 0.0, 0.0]]

Cb[0].extend([0] * (len(Cb[0]) + 1 - len(Cb[0])))

print(Cb)

Here’s a version of code that is more dynamic and return the expected ouptup

Answered By: EL Amine Bechorfa
cb=[[1.0, 0.0, 0.0]]
cb[0].append(0.0)
print(cb)

Output is :

[[1.0, 0.0, 0.0, 0.0]]
Answered By: Roshanak Parnian
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.