Merge Lists in Python

Here are some examples of merging two lists into one. This simple example appends the values from secondList onto firstList.

firstList = ['fido', 'ultra5', '2', '500']
secondList = ['2 x 18g', '250m swap']

for line in secondList:
   firstList.append(line)

The following code merges two lists, but will insert the second list after finding a specific string, in this case a hostname. outerList.pop(0) removes the first element from the list, and then inserts the remaining list into firstList.

import sys

firstList = ['fido', 'ultra5', '2', '500', 'daeo', 'DL580', '8', '128']
secondList = [['fido', '2 x 18g', '250m swap'], ['daeo', '4 x 146g', '16g swap']]

try:
   for outerList in secondList:
      systemName = outerList.pop(0)

      for innerList in outerList:
         indexPos = firstList.index(systemName)
         firstList.insert(indexPos + 1, innerList)
	      
except ValueError:
   print 'ValueError: ', sys.exc_info()[0]



This document was generated using AFT v5.096