Insert items to lists within a list
<p>I want to create a list of multiple lists, considering one list in particular.</p>

<p>For example: I want to add items from <code>a</code>, <code>b</code>, <code>c</code> into <code>x</code> list, and then append <code>x</code> to one main list.</p>

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

a = ['a1', 'b1', 'c1']
b = ['a2', 'b2', 'c2']
c = ['a3', 'b3', 'c3']
</code></pre>

<p>First I need to create a list of lists for <code>x</code>:</p>

<pre><code>x = [[i] for i in x]
</code></pre>

<p>It returns:</p>

<pre><code>out[1]: [[1], [2], [3]]
</code></pre>

<p>Now, I want to add items to those lists:</p>

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

out[2]: [[1, 'a1'], [2, 'b1'], [3, 'c1']]
</code></pre>

<p>And then append to <code>mainlist</code>:</p>

<pre><code>mainlist.append(x)
out[3]: [[[1, 'a1'], [2, 'b1'], [3, 'c1']]]
</code></pre>

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

<pre><code>[[[1, 'a1'], [2, 'b1'], [3, 'c1']], [1, 'a2'], [2, 'b2'], [3, 'c2']], [1, 'a3'], [2, 'b3'], [3, 'c3']]]
</code></pre>

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

<pre><code>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)
</code></pre>

<p>Any suggestions to improve it are appreacited. Thanks!</p>

<p>Just <em>zip</em> <em>x</em> with each of the lists <em>a,b,c</em> using a <em>list comp</em>:</p>

<pre><code>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]
</code></pre>

<p>That will give you:</p>

<pre><code>[[(1, 'a1'), (2, 'b1'), (3, 'c1')], [(1, 'a2'), (2, 'b2'), (3, 'c2')], [(1, 'a3'), (2, 'b3'), (3, 'c3')]]
</code></pre>

<p>If you really want sublists instead of tuples you can call <em>map</em> to map the tuples to lists:</p>

<pre><code> [list(map(list, zip(x, y))) for y in a,b,c]
</code></pre>

<p>If you were going to use a regular loop without the <em>zip</em> logic, you would do something like:</p>

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

<p>Or a list comp version of the same:</p>

<pre><code> [[[x[i], ele] for i, ele in enumerate(y) ] for y in a, b, c]
</code></pre>

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

python list python-3.x