Adding counter/index to a list of lists in Python
<p>I have a list of lists of strings:</p>

<pre><code>listBefore = [['4', '5', '1', '1'],
              ['4', '6', '1', '1'],
              ['4', '7', '8', '1'],
              ['1', '2', '1', '1'],
              ['2', '3', '1', '1'],
              ['7', '8', '1', '1'],
              ['7', '9', '1', '1'],
              ['2', '4', '3', '1']]
</code></pre>

<p>and I would like to add a counter/index in the middle of each list so that the list looks like:</p>

<pre><code>listAfter = [['4', '5', '1', '1', '1'],
             ['4', '6', '2', '1', '1'],
             ['4', '7', '3', '8', '1'],
             ['1', '2', '4', '1', '1'],
             ['2', '3', '5', '1', '1'],
             ['7', '8', '6', '1', '1'],
             ['7', '9', '7', '1', '1'],
             ['2', '4', '8', '3', '1']]
</code></pre>

<p>What would be the easiest way to do so? I could probably loop over the lists and add the index, but is there a cleaner way to do so?</p>

<p>Cheers,
Kate</p>

<p>Edit:
The code I wrote works for me:</p>

<pre><code>item = 1
for list in listBefore:
    list.insert(2,str(item))
    item = item + 1
print listBefore
</code></pre>

<p>I was wondering if there is another way to do so more efficiently or in one step.</p>

<p>Iterate over the parent list with <code>enumerate()</code> to get counter (used as <code>i</code> in the below example) along with list element. In the sublist, insert the <code>i</code> at the middle of sublist using <code>list.insert(index, value)</code> method.
<em>Note:</em> The value of counter i.e. <code>i</code> will be of <code>int</code> type, so you have to explicitly type cast it to <code>str</code> as <code>str(i)</code>before inserting. Below is the sample code:</p>

<pre><code>for i, sub_list in enumerate(my_list, 1):  # Here my_list is the list mentioned in question as 'listBefore'
    sub_list.insert(len(sub_list)/2, str(i))

# Value of 'my_list'
# [['4', '5', '1', '1', '1'], 
#  ['4', '6', '2', '1', '1'], 
#  ['4', '7', '3', '8', '1'],
#  ['1', '2', '4', '1', '1'], 
#  ['2', '3', '5', '1', '1'], 
#  ['7', '8', '6', '1', '1'], 
#  ['7', '9', '7', '1', '1'], 
#  ['2', '4', '8', '3', '1']]
</code></pre>

python list