estebanpdl estebanpdl - 3 months ago 7
Python Question

Insert items to lists within a list

I want to create a list of multiple lists, considering one list in particular.

For example: I want to add items from

a
,
b
,
c
into
x
list, and then append
x
to one main list.

mainlist = []
x = [1, 2, 3] # items will be added hear.

a = ['a1', 'b1', 'c1']
b = ['a2', 'b2', 'c2']
c = ['a3', 'b3', 'c3']


First I need to create a list of lists for
x
:

x = [[i] for i in x]


It returns:

out[1]: [[1], [2], [3]]


Now, I want to add items to those lists:

for item in range(0, len(x)):
x[item].insert(1, a[item])

out[2]: [[1, 'a1'], [2, 'b1'], [3, 'c1']]


And then append to
mainlist
:

mainlist.append(x)
out[3]: [[[1, 'a1'], [2, 'b1'], [3, 'c1']]]


My question is how can I add items from
b
and
c
as I did with
a
list, in order to get this output:

[[[1, 'a1'], [2, 'b1'], [3, 'c1']], [1, 'a2'], [2, 'b2'], [3, 'c2']], [1, 'a3'], [2, 'b3'], [3, 'c3']]]


I tried this, and I got the result, however i think this code could be improved.

item1 = [[i] for i in x]
item2 = [[i] for i in x]
item3 = [[i] for i in x]

for i in range(0, len(item1)):
item1[i].insert(1, a[i])

for i in range(0, len(item2)):
item2[i].insert(1, b[i])

for i in range(0, len(item3)):
item3[i].insert(1, c[i])

mainlist.append(item1)
mainlist.append(item2)
mainlist.append(item3)


Any suggestions to improve it are appreacited. Thanks!

Answer

Just zip x with each of the lists a,b,c using a list comp:

x = [1, 2, 3] # items will be added hear.

a = ['a1', 'b1', 'c1']
b = ['a2', 'b2', 'c2']
c = ['a3', 'b3', 'c3']

main_list = [zip(x, y) for y in a,b,c]

That will give you:

[[(1, 'a1'), (2, 'b1'), (3, 'c1')], [(1, 'a2'), (2, 'b2'), (3, 'c2')], [(1, 'a3'), (2, 'b3'), (3, 'c3')]]

If you really want sublists instead of tuples you can call map to map the tuples to lists:

 [list(map(list, zip(x, y))) for y in a,b,c]

If you were going to use a regular loop without the zip logic, you would do something like:

l = []
for y in a, b, c: 
    l.append([[x[i], ele] for i, ele in enumerate(y)])
print(l)

Or a list comp version of the same:

 [[[x[i], ele] for i, ele in enumerate(y) ] for y in a, b, c]

Presuming all are the same length as x, each i is the index of the current element in y and we match it up with the corresponding element from x which is also exactly what zip is doing.