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

Creating multiple sublists in Python

I have a list J with len(J)=2. I want to create a sublist of each element in J[i] where i=0,1. I present the current and expected output.

J = [[1, 2, 4, 6, 7],[1,4]]
arJ1=[]

for i in range(0,len(J)):
    J1=[J[i]]
    arJ1.append(J1)
    J1=list(arJ1)
print("J1 =",J1)

The current output is

J1 = [[[1, 2, 4, 6, 7], [1, 4]]]

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

J1 = [[[1], [2], [4], [6], [7]], [[1], [4]]]

>Solution :

you can try this,

J = [[1, 2, 4, 6, 7],[1,4]]
new_l = []
for l in J:
    tmp = []
    for k in l:
        tmp.append([k])
    new_l.append(tmp)

print(new_l)

this will give you
[[[1], [2], [4], [6], [7]], [[1], [4]]]

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