You can try this :
Names = [['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration', 1745],
['Bland', 'Theodorick', '1742-03-21', 'M', 'rep', 'VA', '', 1742],
['Burke', 'Aedanus', '1743-06-16', 'M', 'rep', 'SC', '', 0]]
for ele in range(len(Names)):
if Names[ele][7] == 0:
Names[ele][7] = (Names[ele-1][2].split('-'))[0]
print(Names)
Explanation:
Using for-loop
and range(len())
itearte over the length
number of times
for ele in range(len(Names)): #it will iterate over three times as len -> 3
Next check for the year
value at index 7
if it equals to 0
then copy the previous year means the year present in previous iteration step means ele-1
. For example if it is in ele(2nd iteration) then it will fetch the year from ele-1
(1st iteration).
Names[ele][7] = (Names[ele-1][2].split('-'))[0]
The year is combined in date
format. To retrieve only the year use the split()
to split the string using -
as delimiter
'1742-03-21' -> [1742, 03, 21]
So the year is in index 0
.
(Names[ele-1][2].split('-'))[0] -> we get year from here
Finally update the year of current ele
to the one which we got.
Output:
[['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration', 1745], ['Bland', 'Theodorick', '1742-03-21', 'M', 'rep', 'VA', '', 1742], ['Burke', 'Aedanus', '1743-06-16', 'M', 'rep', 'SC', '', '1742']]