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]]
Answers:
Simply append to the inner list using Cb[0].append(0)
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
cb=[[1.0, 0.0, 0.0]]
cb[0].append(0.0)
print(cb)
Output is :
[[1.0, 0.0, 0.0, 0.0]]
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]]
Simply append to the inner list using Cb[0].append(0)
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
cb=[[1.0, 0.0, 0.0]]
cb[0].append(0.0)
print(cb)
Output is :
[[1.0, 0.0, 0.0, 0.0]]