Q: Find and replace empty rows in list width Python I'm using Python 2.7.5 and I have a list looking like this:
('2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '')

The list is full of holes, I want to identify empty rows and fill those with data from the next not empty row. And if there is no next rows containing data I want to set those to 0. Like this:
('2047', '1971', '1919', '1919', '1878', '1878', '1760', '1760', '1760', '1731', '1667', '1667','0','0')

How can I do this with Python? I can do a simple for loop to identify the empty row but I don't know how to fill in the blanks...
Any help would be much appreciated!
Thanks
Martin

A: You can use itertools.groupby for this:
>>> from itertools import groupby
>>> t = ('2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '')
>>> out = []
>>> prev = None
for k, g in groupby(reversed(t)):
    if k == '' and prev is None:
        out.extend('0' for _ in g)
    elif k == '' and prev is not None:
        out.extend(prev for _ in g)
    else:
        for x in g:
            out.append(x)
        prev = x
...             
>>> out.reverse()
>>> out
['2047', '1971', '1919', '1919', '1878', '1878', '1760', '1760', '1760', '1731', '1667', '1667', '0', '0']


A: It is easy to keep record of the previous value in a loop than of the coming values. So my idea is to reverse the list. Replace each empty value by its previous one. Finally reverse the list back and you will get the result.
>>> lst=('2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '')
>>> lst=list(lst[::-1])
>>> pr=0
>>> for j in range(len(lst)):
...     if lst[j]=='':
...        lst[j]=pr
...     else:
...        pr=lst[j]
... 
>>> lst=lst[::-1]
>>> lst
['2047', '1971', '1919', '1919', '1878', '1878', '1760', '1760', '1760', '1731', '1667', '1667', 0, 0]


A: yourList = ['2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '']

lastVal = '0'
for i in range( len(yourList) -1, 0, -1 ):
  if len(yourList[i])==0:
    yourList[i ]= lastVal
  else:
    lastVal = yourList[i]

print yourList

