Inserting elements at specific locations in a list in Python
Question:
I have a list A
. I want to insert elements according to sublists. For example, I want to insert 0
in A[0]
at location 0
. Similarly, I want to insert 1
in A[1]
at location 0
. But I am getting an error. I present the expected output.
import numpy as np
A=[[1, 2, 3],[0, 2, 3],[0, 1, 3],[0, 1, 2]]
for i in range(0,len(A)):
A=A[i].insert(i,0)
print(A)
The error is
in <module>
A=A[i].insert(i,1)
TypeError: 'NoneType' object is not subscriptable
The expected output is
[[0, 1, 2, 3],[1, 0, 2, 3],[2, 0, 1, 3],[3, 0, 1, 2]]
Answers:
You can do the following:
import numpy as np
A=[[1, 2, 3],[0, 2, 3],[0, 1, 3],[0, 1, 2]]
for i in range(0,len(A)):
A[i].insert(0,i)
print(A)
Output:
[[0, 1, 2, 3], [1, 0, 2, 3], [2, 0, 1, 3], [3, 0, 1, 2]]
From doc:
methods like insert
, remove
or sort
that only modify the list
have no return value printed – they return the default None
.
But, nevertheless, inserting in a loop is not efficient as it have to shift all remaining elements rightward; use list comprehension instead:
A = [[i] + A[i] for i in range(len(A))]
I have a list A
. I want to insert elements according to sublists. For example, I want to insert 0
in A[0]
at location 0
. Similarly, I want to insert 1
in A[1]
at location 0
. But I am getting an error. I present the expected output.
import numpy as np
A=[[1, 2, 3],[0, 2, 3],[0, 1, 3],[0, 1, 2]]
for i in range(0,len(A)):
A=A[i].insert(i,0)
print(A)
The error is
in <module>
A=A[i].insert(i,1)
TypeError: 'NoneType' object is not subscriptable
The expected output is
[[0, 1, 2, 3],[1, 0, 2, 3],[2, 0, 1, 3],[3, 0, 1, 2]]
You can do the following:
import numpy as np
A=[[1, 2, 3],[0, 2, 3],[0, 1, 3],[0, 1, 2]]
for i in range(0,len(A)):
A[i].insert(0,i)
print(A)
Output:
[[0, 1, 2, 3], [1, 0, 2, 3], [2, 0, 1, 3], [3, 0, 1, 2]]
From doc:
methods like
insert
,remove
orsort
that only modify the list
have no return value printed – they return the defaultNone
.
But, nevertheless, inserting in a loop is not efficient as it have to shift all remaining elements rightward; use list comprehension instead:
A = [[i] + A[i] for i in range(len(A))]