Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting elements at specific locations in a list in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[0, 1, 2, 3],[1, 0, 2, 3],[2, 0, 1, 3],[3, 0, 1, 2]]

>Solution :

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))]
 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading