I have a 2D Python array (list of lists). I treat this as a 'table'. Now I want to replace the first row and the top row with a header row and column. The row and the header are exactly the same.
I try this using list comprehension. It works out for the 'row' part, but the column part is not very Pythonic yet.
# The header that i want to add
headers = ['foo', 'bar', 'baz', 'other']
l = len(headers) + 1 # The final matrix is one element bigger
# square matrix of random size, filled with data
array = [['xxx' for i in range(l)] for j in range(l)]
# The concise one - add headers to top row
array[0] = ['Title'] + [category for category in headers]
# The ugly one - add headers for the rows
for i in range(l):
array[i][0] = array[0][i]
The final output should look like this (which it does):
[['Title', 'foo', 'bar', 'baz', 'other'],
['foo', 'xxx', 'xxx', 'xxx', 'xxx'],
['bar', 'xxx', 'xxx', 'xxx', 'xxx'],
['baz', 'xxx', 'xxx', 'xxx', 'xxx'],
['other', 'xxx', 'xxx', 'xxx', 'xxx']]
I'm just not so happy with the 'for' loop. How can this be done more Pythonic?