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>You should learn about <code>enumerate</code>, it lets you iterate over the list with two iterators - one (<code>str_list</code> in this case<code>) holds the current item in the list, and the other (</code>i`) holds it's index in the list.</p>

<pre><code>for i,str_list in enumerate(listBefore):
  listBefore[i] = str_list[:len(str_list)//2] + [str(i+1)] + str_list[len(str_list)//2:]
</code></pre>

python list