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]]
Asked By: rajunarlikar123

||

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]]
Answered By: Mattravel

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))]
 
Answered By: RomanPerekhrest
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.