Skip to content
Advertisement

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

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

Advertisement

Answer

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]]]

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement