Creating multiple sublists in Python

Question:

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

||

Answers:

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

Answered By: Abhishek

With simple list comprehension:

res = [[[i] for i in sub_l] for sub_l in J]
print(res)

[[[1], [2], [4], [6], [7]], [[1], [4]]]
Answered By: RomanPerekhrest

You can do in one line with list comprehension:

[[[k] for k in l] for l in J]
Answered By: Talha Tayyab
J = [[1, 2, 4, 6, 7],[1,4]]
arJ1 = []

for in_list in J:
    new_list = []
    for x in in_list:
        new_list.append([x])
    arJ1.append(new_list)

print(arJ1)
Answered By: Peddi Santhoshkumar
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.