nebffa
nebffa

Reputation: 1549

Python - Delete column from a matrix without numPy

this is my first question on here. The question is simple -

# this removes the top list from the list of lists
triangle = [
[3, 0, 0],
[2, 0, 0],
[1, 0, 0]]
del triangle[0]

I want to have a similarly easy way to remove a 'column'. I can of course do this using a for loop, but is there something equivalent to

del triangle[0]

Thankyou

Upvotes: 1

Views: 4609

Answers (2)

panda-34
panda-34

Reputation: 4209

if you want to do this in place without copying the whole list, then something like

all(map(lambda x: x.pop(which_column), triangle))

EDIT. yes, it won't work if there's 0 in the column, just use any other accumulator function

sum(map(lambda x: x.pop(which_column), triangle))

for python 2 where map is not an iterator accumulator is not needed:

map(lambda x: x.pop(1), triangle)

as a side effect, this returns the deleted column which you may use

deleted_column = list(map(lambda x: x.pop(which_column), triangle))

(for python 2 list() wrapper is not needed)

A shorter form would be

sum(i.pop(which_column) for i in triangle)

or

deleted_column = [i.pop(which_column) for i in triangle]

Although I'm not sure if it qualifies as 'without for loop'

P.S. In official Python documentation they use 0-lenqth deque to consume iterators, like this:

collections.deque(map(lambda x: x.pop(which_column), triangle), maxlen=0)

I don't know if it's better than sum(), but it can be used for non-numeric data

Upvotes: 4

Raymond Hettinger
Raymond Hettinger

Reputation: 226466

One way is to use zip() to transpose the matrix, delete the target row, and then zip it back:

>>> def delcolumn(mat, i):
        m = zip(*mat)
        del m[i]
        return zip(*m)

>>> triangle = delcolumn(triangle, 1)
>>> pprint(triangle, width=20)
[(3, 0),
 (2, 0),
 (1, 0)]

Another way is to use list comprehensions and slicing:

>>> def delcolumn(mat, i):
        return [row[:i] + row[i+1:] for row in mat]

>>> triangle = delcolumn(triangle, 1)
>>> pprint(triangle, width=20)
[(3, 0),
 (2, 0),
 (1, 0)]

One last technique is to mutate the matrix in-place using del:

>>> def delcolumn(mat, i):
         for row in mat:
             del row[i]

Upvotes: 3

Related Questions