Search code examples
pythonlistmultidimensional-arraymultiple-columnscontent-length

Finding the Length of a Specific Column in a 2-Dimensional List


In Python 3, if I have a 2-dimensional list in which the last row is not completely filled out (example below), how do I get the length of a specific column?

[[1, 2, 3,],
 [4, 5, 6,],
 [7, 8,]]

For example, columns 0 and 1 have length of 3, but column 2 has a length of 2. Is there a way to do this without using the pandas module?


Solution

  • A column is missing if in a row its index is greater than or equal to the length of the row. That is, if a row only has 2 elements, then columns 0 and 1 exist, but that's it. So we simply need to count the number of rows where the length is greater than the index:

    In [58]: L = [[1, 2, 3,], [4,], [7, 8,]]
    
    In [59]: for row in L: print(row)
    [1, 2, 3]
    [4]
    [7, 8]
    
    In [60]: lens = [sum(len(row) > i for row in L) for i in range(max(map(len, L)))]
    
    In [61]: lens
    Out[61]: [3, 2, 1]
    

    and

    In [62]: L = [[1, 2, 3,], [4, 5, 6,], [7, 8,]]
    
    In [63]: lens = [sum(len(row) > i for row in L) for i in range(max(map(len, L)))]
    
    In [64]: lens
    Out[64]: [3, 3, 2]
    

    The max(map(len, L)) simply finds the number of columns. If you only cared about finding one column in particular, you could just do sum(len(row) > column_number for row in L).