Removing items from a nested list Python

Posted by johntfoster on Stack Overflow See other posts from Stack Overflow or by johntfoster
Published on 2012-03-23T23:10:27Z Indexed on 2012/03/23 23:29 UTC
Read the original article Hit count: 180

Filed under:
|

I'm trying to remove items from a nested list in Python. I have a nested list as follows:

families = [[0, 1, 2],[0, 1, 2, 3],[0, 1, 2, 3, 4],[1, 2, 3, 4, 5],[2, 3, 4, 5, 6]]

I want to remove the entries in each sublist that coorespond to the indexed position of the sublist in the master list. So, for example, I need to remove 0 from the first sublist, 1 from second sublist, etc. I am trying to use a list comrehension do do this. This is what I have tried:

familiesNew = [ [ families[i][j] for j in families[i] if i !=j ] for i in range(len(families)) ] 

This works for range(len(families)) up to 3, however beyond that I get IndexError: list index out of range. I'm not sure why. Can somebody give me an idea of how to do this. Preferably a one-liner (list comprehension). Thanks.

© Stack Overflow or respective owner

Related posts about python

Related posts about python-2.7