My array maximum dimension could be 2x27,but number of columns could be lower than 27.Number of columns depends on some condition.Is good solution to initialize array 2x27 and then delete unnecessary columns or has more elegant way to do this?
3 Answers
No, it makes no particular sense to build a larger array then remove some part of it -- just build what you need. Assuming that by "2d array" you actually mean "list of lists":
def makarray(value, nrows, ncols):
return [[value]*ncols for _ in range(nrows)]
2 Comments
Jesse Aldridge
Ok, I feel stupid now :) Also, I think you might have gotten nrows and ncols backwards...
Alex Martelli
@Jesse, you're right about the cols/rows (guess you can take the guy out of Fortran but you can't take Fortran out of the guy!-) -- editing now, thanks.
Here is a simple way to handle it:
num_rows, num_cols = 2, 27
table = []
for r in range(num_rows):
row = []
table.append(row)
for c in range(num_cols):
row.append(c)
print table
1 Comment
Hamish Grubijan
This is not bad unless you need to shrink / grow the bad boy. Really all depends on what the asker is trying to do.
my_2d_array = [ ["x"] * COLS ] * ROWS