2

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?

1
  • Here's what doesn't work. Looks reasonable in the interpreter but it makes references to the same object, instead of separate objects with separate memory. my_2d_array = [ ["x"] * COLS ] * ROWS Commented Jan 13, 2010 at 0:35

3 Answers 3

3

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)]
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I feel stupid now :) Also, I think you might have gotten nrows and ncols backwards...
@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.
1

For so few elements use a dictionary, with tuples as keys:

dct = {}
dct[(0,0)] = 'X'
if (10,10) in dct:
    dct[(10,10)] += 1
else:
    dct[(10,10] = 0
# Deleting a row / column
dct.pop((10,0))
dct.pop((10,1))
...
dct.pop((10,10))

Dictionaries are very flexible.

Alternatively use a numpy array.

Comments

1

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

This is not bad unless you need to shrink / grow the bad boy. Really all depends on what the asker is trying to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.